Starting with Node.js


1 | Install Node.js


You can easily install Node.js by downloading an installer for your Operating System (OS) or by downloading the source code here: https://nodejs.org/en/ or https://nodejs.org/en/download/.


2 | The node command


The usual way to run a Node.js program is to run the globally available command node (once Node.js is installed on your OS). If your main Node.js application file is app.js, you can execute it by typing:


node app.js

3 | The process module


In computer science, a process is the instance of a computer program that is being executed. Node has a global process object with useful methods and information about the current process.


3.1 | process.argv


The process.argv property holds an array of command line values provided when the current process was initiated. The first element in the array is the absolute path to Node.js, which ran the process. The second element in the array is the path to the file that is running. The following elements will be any command line arguments provided when the process was initiated. Command line arguments are separated from one another with spaces.


Example:


node app.js joe bill jack

In the previous code, there are 3 arguments added to the process.argv array: 'joe', 'bill' and 'jack'.


We can access these values in the app.js file with the following code:


// app.js
let [command, file, ...arguments] = process.argv;
console.log(arguments.join(', '));

The previous code displays 'joe, bill, jack' when executed. We used destructuring assignment and the destructuring dots syntax to assign the command line values to the variable arguments.


3.2 | process.env


Node.js programs can also take input from environment variables. Node.js makes these available though the process.env object. The property names of this object are environment variable names, and the property values (always strings) are the values of those variables.


Here is an example that accesses the NODE_ENV environment variable, which is set to development by default.


console.log(process.env.NODE_ENV); // "development"

We can also create our own environment variables:


process.env.weather = 'Sun is shining';
console.log(process.env.weather); // 'Sun is shining'

3.3 | process.exit()


Node.js programs will gracefully and automatically exit when all the processing is done.


However, Node.js programs are often based on events and event handlers. They do not exit until they are done running the initial file and until all event handlers have been called and there are no more pending events to be emitted. Some programs always listen to event, so they may never exit naturally. In this case, if we want to interrupt the program, we need to force it to do so.


Users can terminate a Node.js program by typing Ctrl-C in the terminal window where the program is running.


A program can also force itself to programmatically exit by calling the method process.exit(). When Node.js runs this line, the process is immediately forced to terminate. This means that all pending operations are going to be ungracefully terminated right away.


The process.exit() method can also take an integer as an argument to signal the Operating System (OS) the exit code. By default, the exit code is 0, which means success. Different exit codes have different meaning, which you might want to use in your own system to have the program communicate to other programs. All of the exit codes can be found here: https://nodejs.org/api/process.html#process_exit_codes.


You can also set the process.exitCode property, so that when the program ends, Node.js returns that exit code.


process.exitCode = 1;

4 | Packages and npm


In Node.js, it is possible to use external code by installing Node.js third-party programs called packages. Any program, even the ones that we create locally, can be turned into packages, and can also be referred as packages. Node.js has its official registry of packages called the npm registry. All packages are available at https://www.npmjs.com/.


Packages can be managed in Node.js thanks to a special package called npm (Node Package Manager). npm is included in every install of Node.js. In particular, we can easily and quickly manage the packages used in our Node.js program by using npm command lines:



Note: yarn and pnpm are alternatives to npm. You can find more info on the official websites:



4.1 | The package.json and the package.lock.json files


The package.json file is a file that holds metadata related to a package, private or public. This file is used to give information to npm that allows it to identify the package as well as handle the package's dependencies. It can also contain information such as the package description, the version of the package in a particular distribution, the license information, and even configuration data - all of which can be vital to both npm and to the end users of the package. The package.json file is normally located at the root directory of a Node.js project.


The package.json file contain a JSON object with several property names and values. This object can be quite big for ambitious projects. Here are the names of the properties we can find in this object:



When Node.js creates the package.json file; it also creates a package-lock.json file. The package-lock.json is here to keep track of the exact version of every package that is initially installed in the current project. This is helpful if we want, for whatever reason, have the exact dependencies in their initial versions.


4.2 | Semantic versioning


in the package.json file, the properties "version", "dependencies", "devDependencies" and "engines" list packages and their versions thanks to standardized versions using the semver convention (semantic versioning). In semantic versioning, all versions have 3 digits, x.y.z:



For a new release, the semantic version is updated with the following rules:



In the package.json file, it is also possible to specify the rules to specify to which versions packages can be updated when using the command npm update. This is done by prefixing the semantic versions with symbols:



5 | Useful npm command lines


5.1 | Initialize a project with the package.json file


# Initialize a project with the package.json file
npm init --yes
# or
npm init -y

The first command line is the standard command line (with a flag using two hyphens) whereas the second command line is the short one (with a flag using one hyphen).


Once a project is initialized with a package.json file, any install of a local package is automatically added to the package.json file and the package.lock.json file.


5.2 | Install packages


When you install a package using npm, you can perform 2 types of installation:



Note: In general, all packages should be installed locally. A package should be installed globally when it provides an executable command that you run from the shell (CLI), and it is reused across projects.


Also, when you install a package locally, you can perform 2 types of installations:



# 1. Install a single package globally
npm install nodemon --global
# or
npm i nodemon -g

# 2. Install several packages globally
npm install nodemon cowsay owlsay --global
# or
npm i nodemon cowsay owlsay -g

# 3. Install a single package as a dependency (locally)
npm install express --save
# or
npm install express
# or
npm i express -S
# or
npm i express

# 4. Install several packages as dependencies (locally)
npm install express ejs cors helmet --save
# or
npm install express ejs cors helmet
# or
npm i express ejs cors helmet -S
# or
npm i express ejs cors helmet

# 5. Install a single package as a devDependency (locally)
npm install dotenv --save-dev
# or
npm i dotenv -D

# 6. Install several packages as devDependencies (locally)
npm install dotenv webpack mocha --save-dev
# or
npm i dotenv webpack mocha -D

# 7. Install all dependencies listed in the package.json file (locally)
npm install
# or
npm i

5.3 | List the installed versions of packages


# List the installed versions of global dependencies
npm list --global
# or
npm list -g

# List the installed versions of local dependencies
npm list --depth=0

# See the installed version of a specific local dependency
npm list cowsay

5.4 | Update packages

# Update all packages according to the update rules of the package.json file
npm update

# Update a specific package according to the update rules of the package.json file
npm update express

5.5 | Uninstall packages


# 1. Uninstall a global package
npm uninstall nodemon --global
# or
npm uninstall nodemon -g

# 2 Uninstall a dependency
npm uninstall express --save
# or
npm uninstall express

# 3. Unistall a development dependency
npm uninstall dotenv --save-dev
# or
npm uninstall dotenv --D

Author: Dimitri Alamkan
Initial publication date:
Last updated: