Reputation: 28746
New to node.js.
I'm setting up integration tests for a node.js app with mocha, following this guide: http://taylor.fausak.me/2013/02/17/testing-a-node-js-http-server-with-mocha/
Created a server as follows:
var http = require('http');
this.server = http.createServer(function (req, res) {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, world!\n');
});
exports.listen = function () {
this.server.listen.apply(this.server, arguments);
};
exports.close = function (callback) {
this.server.close(callback);
};
The listen and close functions are so that:
Question:
How can I create a launch script that calls server.listen on startup? Currently it is launched with with:
"scripts": {
"test": "mocha --reporter spec",
"start": "nodemon server.js"
}
^-- I want to add an invocation of server.listen() to the script above.
Upvotes: 2
Views: 5394
Reputation: 1268
You can test whether the script has been invoked from the command line or require
'd by another script with the following bit of code:
const PORT = process.argv[2] || 8080; // whatever port number
if (require.main === module) {
this.server.listen(PORT); // to start listening
// or, if you are certain that it will always be
// called the same way... you could apply a slice
// of process.argv to server.listen
//
// this.server.listen.apply(this.server, process.argv.slice(2))
//
// https://nodejs.org/api/http.html#http_server_listen_port_hostname_backlog_callback
}
this will start your server listening immediately in the event it was called directly, and wait for listen to be called on the imported module if being used by another script.
you can pass an optional port argument to the npm start script like so:
"start": "nodemon server.js 8001"
Upvotes: 2