在child_process.fork上的Node.js调用函数

我有一个server.js模块,导出一个start()函数来启动我的服务器。 我需要这个模块,并从index.js启动服务器。

我试图通过在child_process.fork调用中启动服务器来单独testingserver.js模块(使用Mocha),但是我看不到如何调用导出的启动函数。

目前,它正在通过将'index.js'传递给fork调用,但是我不知道如何将选项传递给server.js模块(例如发送一个端口号)。

这是我的server.js和使用index.js(它只需要和调用server.start())的unit testing 。

我想直接testingserver.js,所以我可以传递环境variables。

==== ====编辑

我不确定我想通过单独启动服务器获得什么。
我已经改变了testing,只是在前面的块中启动服务器。
build议欢迎。

var assert = require("assert"); var request = require("request"); describe("Server", function(){ var server; var port = 4008; before(function(done){ server = require("../server"); server.start(port); done(); }); it('listens on specified port (' + port + ')', function(done){ request('http://localhost:' + port, function(err, res, body){ assert(res.statusCode == 200); done(); }); }); }); 

您可能想要使用cluster模块,这使得处理过程更简单一些。 以下可能是你所需要的。

 var cluster = require('cluster'); // Runs only on the master process. if (cluster.isMaster) { var environmentVariables = { PORT: 2020 }; var worker = cluster.fork(environmentVariables); // Catch a message from the worker, and then destroy it. worker.on('message', function(message) { if (message.hasOwnProperty('testResult')) { // Kill the worker. worker.destroy(); // Then do something with the result. } }); } // Runs only on a worker process. if (cluster.isWorker) { var server = require('./server'); server.start(); // Do some stuff for tests. // Send the test result. process.send({ testResults: 'pass', failReason: null }); } 

我没有testing过这个,但希望这个要点是清楚的。 您可以在生成工作进程时传入自定义环境variables,然后将工作进程消息作为主结果。 您可能需要处理退出事件以及工人崩溃或挂起时的时间。

另外,你可能应该把process.env.PORT包装在一个parseInt