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.
Node.js Require All Files in a Folder
We can export all modules in a folder by creating a module that exports all the modules.
Then we can import them all at once.
For instance, we can write:
index.js
exports.foo = require("./routes/foo.js");
exports.bar= require("./routes/bar.js");
app.js
const routes = require("./routes");
We can also write:
const fs = require("fs");
const normalizedPath = require("path").join(__dirname, "routes");
fs.readdirSync(normalizedPath).forEach((file) => {
require(`./routes/${file}`);
});
Stringify an Error
We can log an error by looping through the properties of an object.
For instance, we can write:
const error = new Error('error');
const propertyNames = Object.getOwnPropertyNames(error);
for (const prop of propertyNames) {
const descriptor = Object.getOwnPropertyDescriptor(error, prop);
console.log(prop, descriptor);
}
We use the Object.getOwnPropertyNames
method to get the properties of the error
object.
Then we get the descriptors of each property.
Difference Between “process.stdout.write” and “console.log” in Node.js
console.log
calls process.stdout.write
with formatted output.
The code for console.log
is just:
console.log = function (d) {
process.stdout.write(d + 'n');
};
They are pretty much equivalent except for the extra line break.
Set NODE_ENV to production/development in Mac OS or Windows
We can use the export
command to set environment variables in Mac OS.
For instance, we can set the NODE_ENV
by running:
export NODE_ENV=production
In Windows, we can use the SET
command:
SET NODE_ENV=production
We can also set process.env.NODE_ENV
directly:
process.env.NODE_ENV = 'production';
We can set the environment when we run the file by running:
NODE_ENV=production node app.js
It also works in the package.json
scripts
:
{
...
"scripts": {
"start": "NODE_ENV=production node ./app"
}
...
}
Using require in Express Templates
require
is included with CommonJS.
It’s not a part of browser-side JavaScript natively.
To include JavaScript files, we can use the script tag.
Also, we can use CommonJS module.
Or we can use async modules.
Browserify, Webpack, and Rollup can bundle modules into build artifacts usable by the browser.
We can also use ES6 modules natively in browsers with the type attribute set to module
.
For instance, we can write:
script.js
export const hello = () => {
return "Hello World";
}
We can then include script.js
by writing:
<script type="module" src="script.js"></script>
Measure the Execution Time of JavaScript Code with Callbacks
We can use the console.time
and console.timeEnd
methods to measure the time of a script.
For instance, if we have:
for (let i = 1; i < 10; i++) {
const user = {
id: i,
name: "name"
};
db.users.save(user, (err, saved) => {
if(err || !saved) {
console.log("error");
} else {
console.log("saved");
}
});
}
We can call the methods by writing:
console.time("save");
for (let i = 1; i < 10; i++) {
const user = {
id: i,
name: "name"
};
db.users.save(user, (err, saved) => {
if(err || !saved) {
console.log("error");
} else {
console.log("saved");
}
console.timeEnd("save");
});
}
We’ve to pass in the same string to time
and timeEnd
.
Download a File from NodeJS Server Using Express
We can download a file with the res.download
method in an Express route.
For instance, we can write:
const path = reqyire('path');
app.get('/download', (req, res) => {
const file = path.join(`${__dirname}, 'folder', 'img.jpg');
res.download(file);
});
We just get the path and pass it to res.download
.
URl Encode a String in Node.js
We can URI encode a string in Node.jhs with the querystring
module.
For instance, we can write:
const querystring = require("querystring");
const result = querystring.stringify({ text: "hello world"});
Then we get 'text=hello%20world’
for result
.
Get Local IP Address in Node.js
We can get a local IP address in a Node app with the dns
module.
For instance, we can write:
const dns = require('dns');
const os = require('os');
dns.lookup(os.hostname(), (err, addr, fam) => {
console.log(addr);
})
We call lookup
with the hostname to get the IP address from the hostname.
Then addr
has the IP address.
Conclusion
We can get the IP address with the dns
module.
console
has methods to let us measure the timing of code.
We can require files dynamically.
Environment variables can be set dynamically.