# NODE SCRIPTING
notes on creating simple command-line tools with node.
## CREATING THE BASIC FRAMEWORK
* create a new repository on your github
* clone it to your dev folder
* now let's initiate the npm package
* npm init
* then add this to the package.json file:
``` json
"bin": {
"runitbro": "cli.js"
},
```
* then create `cli.js` and add the node shebang at the top: `#!/usr/bin/env node`.
* then add some code to execute when you run the script, we can start with just `console.log("firing the script")`
* then we type `npm link` into terminal (making sure that we are in the root of the project folder)
* once we do that, we should be able to just enter `runitbro` in terminal (anywhere--not just in the project folder) and it should run.
## GETTING ARGUMENTS AND STYLING TEXT
* let's add some packages that are helpful in command-line scripting.
* first, let's add the ability to use different colors and sizes of text
* `npm i figlet`
* `npm i chalk`
* `npm i clear`
* or all with `npm i figlet chalk clear`
* now let's require those in and use them
``` js
var figlet = require('figlet');
var clear = require('clear');
var chalk = require('chalk');
clear();
console.log(figlet.textSync('title'));
console.log(chalk.magenta('colored text'))
```
* for getting arguments, we'll use `yargs`, so `npm i yargs` to install, then the basic idea is
``` js
var yargs = require('yargs').argv;
console.log(JSON.stringify(yargs, null, 4))
```
## RUNNING CHILD PROCESSES
[article on exec vs spawn](https://stackabuse.com/executing-shell-commands-with-node-js/)
## EXAMPLES OF COOL THINGS TO DO
## PUBLISHING ON NPM
1. let's get set up on NPM so that we can publish this thing later.
### youtube-dl concept
see if you can convert this to a node script!!
``` js
#! /usr/bin/env zsh
echo "rocking the party"
VIDEO_TITLE=$(youtube-dl -e --get-title "$1")
echo "we are about to rock the party by downloading $VIDEO_TITLE"
youtube-dl -f 'bestvideo[ext=mp4]+bestaudio[ext=m4a]/best[ext=mp4]/best' -o "~/Desktop/_rtp/%(title)s-%(id)s.%(ext)s" "$1"
echo "all done downloading. we are now ready to rock the party"
```
### ffmpeg compressing
``` js
var transcodeFile = async function(file, proxyPath, options){
await cp.spawnSync('ffmpeg', [
'-i', file,
'-c:v', 'libx264',
'-pix_fmt', 'yuv420p',
// '-vf', ('scale='+ outputWidth +':'+outputHeight ),
'-preset', 'slow',
'-crf', (options && options.crfVal) ? options.crfVal : '23',
'-ac', '2',
'-c:a', 'aac',
'-b:a', '128k',
proxyPath
], {
stdio: [
0, // Use parent's stdin for child
'pipe', // Pipe child's stdout to parent
2 // Direct child's stderr to a file
]
});
}
```
### accessing data from APIs