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.
Get Data from fs.readFile
We can call the readFile
method from the fs
module to tread files.
For instance, we can write:
fs.readFile('./foo.txt', (err, data) => {
if (err) {
throw err;
}
console.log(data);
});
We pass in the path and then read it as a binary file.
data
has the file content and err
is the error object that’s set when an error is encountered.
There’s also the fs.readFileSync
method:
const text = fs.readFileSync('./foo.txt', 'utf8');
console.log(text);
Get a URL Parameter in Express
To get a URL parameter in an Express app, we can use the req.params
property to get the URL parameter.
For instance, we can write:
app.get('/tags/:tagId', (req, res) => {
res.send(req.params.tagId);
});
Then if we make a GET request to /tags/2
, we get 2 as the value of req.params.tagId
.
To get a value from a query parameter, we can use the req.query
property:
app.get('/foo', (req, res) => {
res.send(req.query.tagId);
});
Then if we make a request to /foo?tagId=2
, req.query.tagId
would be 2.
Render Basic HTML View
We can render HTML by using include
to include HTML file in our Jade view.
For instance, we can write in views/index.jade
:
include plainHtml.html
Then in views/plainHtml.html
, we can write normal HTML”
<!DOCTYPE html>
...
And we render index.jade
with:
res.render(index);
NodeJS Support for import/export ES6 (ES2015) Modules
If our app is running on Node 13.2.0 or above, we can enable ES6 module support by adding the following to package.json
:
{
"type": "module"
}
With Node 13.1.0 or below, we can write:
node -r esm main.js
We turn on ES module support by using esm
.
We just run npm i esm
to add esm
to our Node project.
Use underscore.js as a Template Engine
We can use the template
method to pass in our HTML template string.
For instance, we can write:
const template = _.template("<h1>hello <%= name %></h1>");
template
is a function that takes an object with the placeholders.
Then name
is the placeholder that we can pass in.
For instance, we can write:
const str = `template({ name: 'world' });`
Then str
would be '<h1>hello world</h1>’
.
<%= %>
means to print some value in the template.
<% %>
executes some code.
<%- %>
prints some values with the HTML escaped.
Start Script Missing Error When Running npm start
To solve this error, we can add the start
script to package.json
by putting it in the scripts
section.
For instance, we can write:
"scripts": {
"start": "node app.js"
}
The script with the key start
will run when we run npm start
.
Node.js Heap Out of Memory
We can increase the memory limit of Node apps by setting the max-old-space-size
option.
For instance, we can write:
node --max-old-space-size=2048 app.js
to increase the memory limit to 2 GB.
We can also set it in the NODE_OPTIONS
environment variable:
export NODE_OPTIONS=--max_old_space_size=2048
Callback After All Asynchronous forEach Callbacks are Completed
We can use the for-await-of loop to loop through promises.
For instance, we can write:
const get = a => fetch(a);
const getAll = async () => {
const promises = [1, 2, 3].map(get);
for await (const item of promises) {
console.log(item);
}
}
This will run each promise sequentially with a loop.
This is available since ES2018.
Format a UTC Date as a YYYY-MM-DD hh:mm:ss
String
We can use the toISOString
method to format a Date
instance into a date string in the ‘YYYY-MM-DD hh:mm:ss’ format.
For instance, we can write”
const str = new Date()
.toISOString()
.`replace(/T/, ' ')
.replace(/..+/, '');`
We replace the T
with an empty string, and replace the text after the dot with an empty string.
Then we get '2020–06–04 16:15:55'
as the result.
Conclusion
Underscore has a template
method.
readFile
can read files.
We can get query parameters in Express.
The memory limit of Node apps can be increased.
Jade templates can include HTML partial views.