NodeJS Introduction
Node arguments and environment variables
Suppose you have a Node script with name argv.js
with the following content.
console.log(process.argv);
Now run the above script with the following arguments.
node --trace-uncaught argv.js --arg1 --arg2 filename
The process.argv
array stores space-separated arguments that you pass to the script. The first element of this array is the path to the Node executable. The second element is the path to the Node script. The remaining elements are the arguments you pass when you run the script. Note that --trace-uncaught
is consumed by the Node interpreter and didn't appear in the arguments array.
[
'C:\\Program Files\\nodejs\\node.exe',
'C:\\Users\\User\\Repositories\\JavaScript\\backend\\argv.js',
'--arg1',
'--arg2',
'filename'
]
The environment variables are available to access from the process.env
object. You can evaluate a one-liner script and print the results by using the following command:
node -p 'process.env'
Error handling
If you don't want uncaught exceptions to cause your program to completely crash, register a global handler function that will be invoked instead of crashing.
process.setUncaughtExceptionCaptureCallback((e) => {
console.error("Uncaught exception:", e);
});
Similarly, register a global handler function to deal with rejected promises.
process.on("unhandledRejection", (reason, promise) => {
console.error(reason, promise);
});
Package manager
To use npm package manager in your project, you first need to initialize the project by running npm init
and specifying project details. The npm will create a file package.json
where all the details of the project are stored.
You install other packages for your project by running npm install packagename
, which will put all the dependencies in ./node_modules/
directory and update the package.json
file with details about the installed dependencies. Later you can run npm install
to install all the dependencies on a new system based on package.json
file.
Modules
You can use either ES6 modules or CommonJS modules in Node, but not both. In order to differentiate which module system you are using, you have three options:
- Use extension
.mjs
for ES6 modules, or.cjs
for CommonJS modules. - Specify the
type
property inpackage.json
file to "module" for ES6 modules, or "commonjs" for CommonJS modules (which is the default value). Clean the cache by typingnpm cache clean --force
in the terminal if there are any errors.
Note that you can load a CommonJS module using the import
keyword of the ES6 modules, but the reverse is not allowed.
You import CommonJS modules the following way.
const fs = require("fs");
Alternatively, you import ES6 modules with the following syntax.
import fs from "fs";