简体   繁体   English

启动时的node.js运行方法

[英]node.js run method on startup

New to node.js. 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/ 我正在按照此指南为带有mocha的node.js应用设置集成测试: http : //taylor.fausak.me/2013/02/17/testing-a-node-js-http-server-with-摩卡/

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: 监听和关闭功能使:

  • require('server') is idempotent require('server')是幂等的
  • server can be started and stopped in tests 可以在测试中启动和停止服务器

Question: 题:

How can I create a launch script that calls server.listen on startup? 如何创建启动时调用server.listen的启动脚本? 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. ^-我想在上面的脚本中添加server.listen()的调用。

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: 您可以使用以下代码测试脚本是否已从命令行调用或是否require其他脚本执行:

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: 您可以将可选的port参数传递给npm start脚本,如下所示:

"start": "nodemon server.js 8001"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM