Like any kind of apps, there are difficult issues to solve when we write Node apps.
In this article, we’ll look at some solutions to common problems when writing Node apps.
Pass Command-Line Arguments to a Node.js Program
We get command line arguments by using the process.argv
property.
It’s an array with all the arguments including node
and the script name.
'node'
is always the first entry.
The script name is the 2nd entry.
The rest of the arguments are the remaining entries.
For instance, if we have:
node foo.js one two=three four
Then node
is the first entry of process.argv
, foo.js
is the 2nd, one
is the 3rd, and so on.
Writing files in Node.js
We can use the writeFile
method to write a file in a Node app.
For instance, we can write:
const fs = require('fs');
fs.writeFile("/foo.txt", "hello world!", (err) => {
if (err) {
return console.log(err);
}
console.log("file saved");
});
We call writeFile
to write the file.
The first argument is the path to the file.
The 2nd is the content of the file.
The callback is called when the file writing process ends.
err
is the error object and it’s defined when an error is encountered.
There’s also a synchronous version call writeFileSync
.
We can use it by writing:
fs.writeFileSync('/foo.txt', 'hello world');
The first argument is the file path.
The 2nd is the content.
How to Debug Node.js Applications
We can use the node-inspector
package to debug Node apps.
We can install it by running:
npm install -g node-inspector
to install it globally.
Then we run node-debug app.js
to run it with node-inspector
which lets us debug it with breakpoints, profiling, etc.
We can also run node inspect app.js
to run app.js
with the debugger.
Read Environment Variables in Node.js
We can read environment variables in Node apps by using the process.env
object.
For instance, if we have the environment variable FOO
, we can write:
process.env.FOO
Remove Empty Elements from an Array in Javascript
To remove empty from a JavaScript array, we can use the filter
method.
For example, we can write:
const arr = [0, 1, null, undefined, 2,3,,,,6];
const filtered = arr.filter((el) => (el !== null || typeof el !== 'undefined'));
This will return an array created from arr
with all the null
and undefined
removed.
Using async/await with a forEach loop
We can use async
and await
with the for-of loop.
For instance, we can write:
const printFiles = async (filePaths) => {
for (const file of filePaths) {
const contents = await fs.readFile(file, 'utf8');
console.log(contents);
}
}
We use the promisified version of readFile
to read the file inside each iteration of the for-of loop.
To run promises in parallel, we can use the Promise.all
method.
For instance, we can write:
const printFiles = async (filePaths) => {
await Promise.all(filePaths.map(async (file) => {
const contents = await fs.readFile(file, 'utf8')
console.log(contents)
}));
}
We call map
to filePaths
to map the paths to promises.
Then we call Promise.all
on the array of promises.
Get a List of the Names of All Files Present in a Directory in a Node App
We can get a list of names of all files in a directory by using the readdir
or readdirSync
method.
For example, we can write:
const fs = require('fs');
fs.readdir('/tesrDir', (err, files) => {
files.forEach(file => {
console.log(file);
});
});
files
have the array of file strings, buffer, or directory entries.
To read a directory synchronously, we can write:
const fs = require('fs');
fs.readdirSync('/testDir').forEach(file => {
console.log(file);
});
We read a directory synchronously.
Parse JSON with Node.js
We can require JSON files or parse them with JSON.parse
.
For example, we can write:
const config = require('./config.json');
or:
const config = require('./config');
The extension is optional.
Also, we can use JSON.parse
to parse JSON strings.
Conclusion
We can get command-line arguments with process.argv
.
Environment variables are read into the process.env
object.
require
can be used to import JSON files.
The fs
module has methods to read and write files.
The for-of loop can run promises sequentially.