Skip to content
On this page


Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

Useful for running Javascript on a server with access to local system resources.



Parameters / Args

var args = process.argv.slice(2);
javascript - How do I pass command line arguments to a Node.js program? - Stack Overflow

For more involved command line parameter parsing:
GitHub - substack/minimist: parse argument options
Process | Node.js v17.1.0 Documentation
node pass parameters to script at DuckDuckGo

Sample Script

See also files

#!/usr/bin/env node

var fs = require('fs');

var args = process.argv.slice(2);
console.log("Parameters passed in: ", args);

// require arguments
if (args.length == 0) {
  console.log("template.js [source] [destination]");

console.log("Directory contents:", args[0]);
// for scanning a directory
fs.readdir(args[0], (err, files) => {
  files.forEach((file) => {
    console.log(`[${file}](${file})  `);

// For system calls
// const { exec } = require("child_process");

// exec(`ls -la ${args[0]}`, (error, stdout, stderr) => {
//     if (error) {
//         console.log(`error: ${error.message}`);
//         return;
//     }
//     if (stderr) {
//         console.log(`stderr: ${stderr}`);
//         return;
//     }
//     console.log(`stdout: ${stdout}`);
// });

// For reading files and loading them as JSON

// var obj;
// fs.readFile(args[0], 'utf8', (err, data) => {
//   if (err) throw err;

//   // parse data as json:
//   // obj = JSON.parse(data);

//   // iterate over lines:
//   const lines = data.split('\n');
//   for(var i=0; i < lines.length; i++) {
//     console.log(lines[i]);
//   }
// });

Import vs Require

Cannot use import statement outside a module

To use ESModules syntax, need to switch package. (Note: all code will need to follow this pattern)

"type": "module"

Or Use commonjs syntax instead of es module syntax:

module.exports.func = function (){
    console.log("Hello World");
const myMod = require("./mod")

ES6 modules use the import syntax. Seems like the way to go moving forward.
node.js - The difference between "require(x)" and "import x" - Stack Overflow
javascript - Using Node.js require vs. ES6 import/export - Stack Overflow
javascript require vs import at DuckDuckGo

Local Development
work on npm module in development at DuckDuckGo
An Absolute Beginner's Guide to Using npm - NodeSource
How to smoothly develop node modules locally using npm link

Module Not Found

Make sure you've actually installed the module if you get a message like MODULE_NOT_FOUND

Package Managers

Package managers ensure that all of the modules that your application depends on are compatible and available to the local code base.

Types of dependencies

Dependencies serve many different purposes. Some dependencies are needed to build your project, others are needed when you’re running your program. As such there are a number of different types of dependencies that you can have (e.g. dependencies, devDependencies, and peerDependencies).

Choosing a package manager

NPM vs PNPM vs Yarn

The answer? Use what the project is using. Be consistent.

All are good. No need to get hung up here. See what works best and make a change when necessary.


NPM is the default package manager for Node. In some environments, it may be all you have access to.

Install packages

Install everything as configured in package.json file

npm install

Calls to

npm install --save [package name]


npm install --save-dev [package name]


npm install --save-optional [package name]

will update the package.json to list your dependencies.

Upgrade / Update packages

To upgrade a package that has already been installed, use either:

npm install [package name]@latest


npm update [package name]

Remove packages

To remove a dependency:

npm uninstall <name> --save


If you have a bit more control over the hosting environment and can install a user level package manager, pnpm is a good option.

PNPM uses links to node modules so you don't end up with 100 copies of the same module on your local drive. This is useful in development when you may want to use a large development module in multiple projects.

With node:

curl -f | node - add --global pnpm

With npm:

npm install -g pnpm


npx pnpm add -g pnpm

One downside is that it is not included by default in the main docker node image. May not be necessary to use it in a container context. pnpm is more helpful on development.

One downside is the addition of _tmp_* directories. These are easy to ignore in VSCode


It should be available in most Node containers.

Once you have yarn available, you can add packages as a requirement with:

yarn add <name>

or as a dev dependency with:

yarn add <package...> [--dev/-D]

To install a package globally, the order of the parameters is important:

yarn global <add/bin/list/remove/upgrade> [--prefix]

To remove a dependency

 yarn remove <name>

Note: manually deleting from package.json removes the dependency from the project, but will not remove the files from node_modules of the local instance.

Reinstall Modules

Reinstalling a package after just deleting the node module works with:

yarn install --check-files


Install / update yarn:

npm install -g yarn

or use a system level package manager

curl -sS | sudo apt-key add -

echo "deb stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

then, with apt-get:

sudo apt-get install --no-install-recommends yarn


Lock files

Is it really a good idea to track lock files under version control? Seems like it adds a lot of noise to the process

Yes, it can add noise if you manage it manually. However, without it you may run into situations where deployments to a different environment may not work due to different versions of modules being installed. It's better to test with a set of locked versions. In that case, lock files are necessary.

Resolve yarn.lock conflicts

It's as easy as running yarn or yarn install to automatically resolve version control conflicts in a yarn.lock file. Sweet!

Resolving package-lock.json conflicts

Occasionally, two separate calls to npm install will create package locks that cause merge conflicts in source control systems. As of npm@5.7.0, these conflicts can be resolved by manually fixing any package.json conflicts, and then running npm install [--package-lock-only] again. npm will automatically resolve any conflicts for you and write a merged package lock that includes all the dependencies from both branches in a reasonable tree. If --package-lock-only is provided, it will do this without also modifying your local node_modules/.

To make this process seamless on git, consider installing npm-merge-driver, which will teach git how to do this itself without any user interaction. In short:

$ npx npm-merge-driver install -g

will let you do this, and even works with pre-npm@5.7.0 versions of npm 5, albeit a bit more noisily. Note that if package.json itself conflicts, you will have to resolve that by hand and run npm install manually, even with the merge driver.


See also

Process Monitoring

If you have a service running live using a node based (e.g. express) server, a monitoring tool can make sure it stays up. Options include...


Docker is a great option.

pm2 - Google Search
PM2 - Home

GitHub - remy/nodemon: Monitor for any changes in your node.js application and automatically restart the server - perfect for development
nodemon vs pm2 - Google Search

Environment Variables (.env) dotenv

Variables set in a .env file are automatically loaded by node and made available via process.env.* variables.

Try out a ui/.env file. Is the value available via process.env.whatever?

Many frameworks leverage these variables for configuration.


See what the latest versions of node are:


Node Version Manager - Simple bash script to manage multiple active node.js versions

Visit the site for the latest version of the command

curl -o- | bash

Open a new shell and verify with:

command -v nvm

Clean up old (non-nvm) node version(s):

npm ls -gp --depth=0 | awk -F/ '/node_modules/ && !/\/npm$/ {print $NF}' | sudo xargs npm -g rm

Install Node via NVM:

nvm install node

To install a specific version of node, use:

nvm install 14

To see what version is currently installed

nvm ls # this should be equivalent to `node -v`

To see versions available to be installed via nvm

nvm ls-remote

To install the latest lts version of node:

nvm install --lts

I needed to add the following to my .bashrc file in order for VSCode to see the new version of node:

PATH="/usr/local/bin:$(getconf PATH)"


Nodesource is another popular way to install node


Docker containers are a great way to ensure you're running the node environment that you think you're running.

Containers for Node applications are maintained here

In docker-compose.yml, this is a good place to start

image: node:lts

If you're using a container that does not have Node installed (e.g. Centos), installing from seems like the best option

RUN curl -sL | bash # for node version 10.x
RUN yum -y install nodejs
RUN node --version # optional to check that it worked
RUN npm --version # optional to check that it worked

NVM is tricky to use in a container:

# nvm environment variables
ENV NVM_DIR /usr/local/nvm

# Install NVM for installing node
RUN curl -o- | bash

RUN source $NVM_DIR/ \
    && nvm install $NODE_VERSION \
    && nvm alias default $NODE_VERSION \
    && nvm use default

NPM Packages & Docker

Official documentation for dockerizing node applications:

May be possible to minimize the number of npm packages pulled down during an image build:

Looks like Seth has another tactic for this here: