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:
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
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.
node app.js joe bill jack
In the previous code, there are 3 arguments added to the
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
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.
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:
- We can install, uninstall or upgrade packages.
- We can automatically track which packages (called dependencies in this context) and which versions of packages we use in our program.
- We can automatically create a package.json file containing metadata about our Node.js program.
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:
"name"sets the project package.
"author"sets the author's information.
"contributors"sets the contributors' information in an array.
"bugs"links to the package issue tracker, most likely a GitHub issues page.
"homepage"links to the package homepage.
"version"indicates the current version of the package.
"license"Indicates the license of the package.
"keywords"lists keywords related to the package in an array.
"description"is a brief description of the package.
"repository"specifies where this package repository is located.
"main"sets the entry point for the package.
private"if set to
trueprevents the package from being accidentally published on the npm registry.
scripts"defines a set of Node.js scripts you can run directly from the Node.js CLI by typing the command line
npm run <scriptName>.
"dependencies"sets a list of npm packages installed as dependencies (more on this below) and specifies to which version the packages can be updated to with the command line
devDependencies"sets a list of npm packages installed as development dependencies (more on this below) and specifies to which version the packages can be updated to with the command line
"engines"sets which versions of Node.js this package works on.
"browserslist"is used to tell which browsers (and their versions) you want to support.
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
"engines" list packages and their versions thanks to standardized versions using the semver convention (semantic versioning). In semantic versioning, all versions have 3 digits,
- The first digit is the major version.
- The second digit is the minor version.
- The third digit is the patch version.
For a new release, the semantic version is updated with the following rules:
- The major version is incremented by 1 when incompatible (or breaking) changes are introduced.
- The minor version is incremented by 1 when a functionality is added in a backward-compatible manner.
- The patch version is incremented by 1 when backward-compatible bug fixes are implemented.
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:
^: It will only do updates that do not change the leftmost non-zero number. If we write
^0.13.0, when running
npm update, it can update to
0.13.2, and so on, but not to
~: if we write
npm update, it can update to patch releases:
0.13.1is OK, but
>: we accept any version higher than the one you specify.
>=: we accept any version equal to or higher than the one you specify.
<=: we accept any version equal or lower to the one you specify.
<: we accept any version lower than the one you specify.
=: we accept that exact version.
-: we accept a range of versions. Example:
2.1.0 - 2.6.2.
||: we combine sets. Example:
< 2.1 || > 2.6.
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:
- a global install. A package installed globally is installed in a global directory. This global directory can be known by typing the following command line:
npm root -g. All global packages are put in this single directory defined by our system, regardless of where we run the
npmcommand line to install a package globally.
- a local install. A package installed locally is added in the directory
node_modulesat the root of the current Node.js project (where we run the command line to install a package locally).
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:
- Install a package as a dependency. In this case, the package is automatically listed in the
dependenciesarray of the package.json file .
- Install a package as a development dependency or devDependency. In this case, the package is automatically listed in the
devDependenciesarray of the package.json file, . Development dependencies are intended as development-only packages, that are unneeded in production. They are usually testing packages. In a production environment, typing the command line
npm install --productionwill only install the packages listed in the
dependenciesarray, and not the devDependencies listed in the
# 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: