Skip to content

Instantly share code, notes, and snippets.

@wojnar48
Last active November 4, 2021 03:59
Show Gist options
  • Save wojnar48/26c8a0d3bc74e4b3d0f11311db36da52 to your computer and use it in GitHub Desktop.
Save wojnar48/26c8a0d3bc74e4b3d0f11311db36da52 to your computer and use it in GitHub Desktop.
cli-notes

CLI Notes

Useful Commands

# Make a local npm package usable globally
npm link
## Unlink a package (same as running: npm install -g <pkg_name>)
npm uninstall -g <pkg_name>
# Check if user is logged into npm
npm whoami
# Create a nested directory tree
mkdir -p /path/to/dir
# Change ownership of directory tree to current user
sudo chown -R $(whoami) /path/to/dir
# Make a file executable by current user
sudo chmod +X /path/to/file

Publishing an npm package

  1. Comming the changes that are meant to be released (RELEASE: x.x.x).
  2. Run npm version major|minor|patch 'RELEASE x.x.x.
  3. Run npm publish.

Handling unhandled errors

At the top level of the file define:

process.on('unhandledRejection', () => {
  // ...do something
});

Node process custom error handling

We can use the global process which is just an instance of an EventEmitter so we can use .on to listen for events.

process.on('exit', () => {
  //...logic
});

process.on('exit', () => {
  //...logic
});

// Node best practice is to set the exit code on process to 1 (Fatal Execution Error)
process.exitCode = 1; 

Node Event Loop

Despite JS being single threaded, the Event Loop allows Node to have non-blocking IO operations by offoading a lot of the work to the os kernel.

TODO(SW): See talk about the Node Event Loop by Bert Belder:

process

Global that gives use control over the currently running in Node

// Prints the current working directory of the Node process
process.cwd() 

// Variables defined in the Node process
process.env

stdin, stdout and stderr

Standard input, output and error are channels for communicating between the terminal and a process.

To send the standard input of a process to the standard error:

process.stdin.pipe(process.stdout);

process.argv

Give the process a reference to the array containing the inputs passed into a program. The first 2 elements of process.argv are always the executable responsible for running the process and the path of the file being executed.

// To obtain arguments passed to the program
let args = process.argv.slice(2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment