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 Variable from Jade Template File to a Script File
To pass a variable in a Jade template to a script, we can interpolate the script code.
For instance, we can write:
app.get('/', (req, res) => {
res.render( 'index', { layout: false, name: 'bar' } );
});
index.jade
script.
name="#{name}";
We use the script
tag and interpolated the name
variable in index.jad
.
Mongoose Select a Specific Field with find
We can select a specific field with find
by passing the field name as the argument.
For instance, we can write:
app.get('/name', (req, res, next) => {
dbSchemas.Foo.find({}, 'name', (err, val) => {
if(err) {
return next(err);
}
res.send(val);
});
});
We select a Foo
document’s name
field by passing the field name as the 2nd argument.
Difference Between async.waterfall and async.series
async.waterfall
lets us pas results to the next function.
async.series
pass all results to the final callback.
Write Asynchronous Functions for Node.js
We write callbacks that have the err
for the error object and the result
aS parameters.
For instance, we can write:
file.read('/foo.txt', (err, result) => {
if (err) {
return console.log(err);
}
doSomething(result);
});
The arguments before the callback is anything we want to use with read
.
And the callback is a Node style callback with the err
object as the first parameter.
result
has the computed results in the 2nd parameter.
Configuring Region in Node.js AWS SDK
We can configure the AWS region with the AWS.config.update
method.
For example, we can write:
const AWS = require('aws-sdk');
AWS.config.update({ region: 'us-east-1' });
to configure the region.
Pass Parameter to a Promise Function
To pass parameters to a promise function, we create a function that takes the parameter we want and returns the promise inside it.
For instance, we can write:
const login = (username, password) => {
return new Promise((resolve, reject) => {
//...
if (success) {
resolve("success");
} else {
reject(new Error("error"));
}
});
}
We return the promise by using the Promise
constructor.
username
and password
are the parameters we passed in.
Then we can use it by writing:
login(username, password)
.then(result => {
console.log(result);
})
We use then
to get the value we passed into resolve
.
Shell Command Execution with Node.js
To run shell commands in Node apps, we can use the child_process
module.
For instance, we can write:
const spawn = require('child_process').spawn;
const child = spawn('ls', ['-l']);
let resp = "";
child.stdout.on('data', (buffer) => {
resp += buffer.toString()
});
child.stdout.on('end', () => {
console.log(resp)
});
We use the child_process
‘s spawn
method.
Then we pass in the command as the first argument to spawn
.
And the command line arguments as the 2nd argument.
Then we can watch for the results with the child.stdout.on
method.
We listen to the 'data'
event to get the output and concatenate the parts that are sent.
And we listen to 'end'
to get the whole result when it ends.
Monitor Memory Usage of Node.js Apps
We can use the node-memwatch package to watch for memory usage of a Node app.
We can install it by running:
npm install memwatch
Then we can use it by writing:
const memwatch = require('memwatch');
memwatch.on('leak', (info) => {
//...
});
We watch for memory leaks with the on
method.
info
has information about the leak.
It has something like:
{
start: Fri, 29 Jun 2020 15:12:13 GMT,
end: Fri, 29 Jun 2020 16:12:33 GMT,
growth: 67984,
reason: 'heap growth over 5 consecutive GCs (20s) - 11.67 mb/hr'
}
It’ll show us the growth in memory usage.
There also methods for watching heap usage and diffing memory usage in different times.
The built-in process
module has the memoryUsage
method to get the memory usage of our app.
For instance, we can write:
process.memoryUsage();
to get the memory usage.
Conclusion
We can watch for memory usage with the process
module or 3rd party modules.
To pass data to a script tag in a Jade template, we can interpolate the code.
We can return a promise in a function if we want a promise with our own parameters.
Mongoose can be used to find data with a given field.