As with any kind of app, 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.
Fix NPM Error on Windows Looking for Tools Version
If we install native Node packages on Windows, we may run into errors that look something like:
MSBUILD : error MSB4132: The tools version "2.0" is unrecognized. Available tools versions are "4.0".
To fix this, we can run:
npm install --global --production windows-build-tools
in admin mode to install the build tools for Windows to compile those packages.
Use a Custom Express Server in Supertest
We have to export out Express server so that it can be tested with Supertest.
For instance, we can write:
app.js
//...
const app = express();
//...
module.exports = app;
Then in our test, we can write:
const request = require('supertest');
const app = require('./app');
describe('POST /', () => {
it('should make request with foo', (done) => {
request(app)
.post('/')
.send({
'foo': 'bar'
})
.expect(200)
.end((err, res) => {
console.dir(err);
console.dir(res);
//...
done();
})
})
})
We pass in the app
which exported into the request
function to make a request with our Express app.
Get Query String Params with Koa Router
To get a query string parameter with the Koa router, we can use the ctx.request.query
property.
For instance, we can write:
import koaRouter from 'koa-router';
const router = koaRouter({
prefix: '/foo'
});
router.get('/', async (ctx) => {
console.log(ctx.request.query);
});
to get the parsed query parameters.
We can also use ctx.query
for short:
import koaRouter from 'koa-router';
const router = koaRouter({
prefix: '/foo'
});
router.get('/', async (ctx) => {
console.log(ctx.query);
});
Accessing the Exit Code and stderr of a System Command
We can access the exit code and stderr of a system command by getting them from the error
object.
For instance, if we’re using execSync
to run our command, then we can write:
const childProcess = require('child_process');
const cmd = 'some command';
try {
childProcess.execSync(cmd).toString();
} catch (error) {
console.log(error.status);
console.log(error.message);
console.log(error.stderr);
console.log(error.stdout);
}
We call execSync
with a command.
Then we get the error with the catch
block.
status
has the exit code.
message
has error messages.
stderr
has the full error output.
stdout
has the standard output.
If we use exec
, we can get the error from the callback.
const childProcess = require('child_process');
const cmd = 'some command';
child_process.exec(cmd, (err, stdout, stderr) => {
console.log(stdout)
console.log(stderr)
console.log(err)
}).on('exit', code => console.log(code))
We can get the stdout
and stderr
from the callback.
The exit code can be obtained by listening to the exit
event.
It takes a callback with the exit code, which is the value of code
.
err
has the errors encountered.
Node.js server.address().address Returns :: in an Express App
To make server.address
return an IP address, we’ve to specify the IP address specifically with listen
.
For example, we can write:
const express = require('express');
const app = express();
const server = app.listen(8888, "127.0.0.1", () => {
const { address, port } = server.address();
console.log(`running at http://${host}:${port}`);
});
We pass in the IP address as the 2nd argument.
Then server.address
will get the host
, which has the IP address, and port
, which has the port.
Unit Test an Event Being Emitted in Mocha
We can listen to events in our Mocha tests.
For instance, we can write:
it('should emit an event', function(done){
this.timeout(1000);
eventObj.on('event', () => {
// run assertions...
done();
});
});
We call this.timeout
to make sure that the test times out with an error if the event isn’t received in 1 second.
Then we can listen to the event
event emitted by eventObj
and run any assertions we want with it.
After that, we call done
to move on to other pieces of code.
Conclusion
We can pass the IP address on listen
to get the IP address the app is listening to with server.address()
. Errors and exit code for shell commands can be retrieved with exec
and execSync
. We’ve to install windows-build-tools
globally to fix any errors with build native packages. To test our Express app with Supertest, we’ve to import our Express app object and pass it to Supertest’s request
function before we make our request.