以下是我的集群Express应用程序的简化版本:
/index.js
module.exports = process.env.CODE_COV
? require('./lib-cov/app')
: require('./lib/app');
Run Code Online (Sandbox Code Playgroud)
/lib/app.js
var cluster = require('cluster'),
express = require('express'),
app = module.exports = express.createServer();
if (cluster.isMaster) {
// Considering I have 4 cores.
for (var i = 0; i < 4; ++i) {
cluster.fork();
}
} else {
// do app configurations, then...
// Don't listen to this port if the app is required from a test script.
if (!module.parent.parent) {
app.listen(8080);
}
}
Run Code Online (Sandbox Code Playgroud)
/test/test1.js
var app = require('../');
app.listen(7777);
// send requests to app, then assert the response.
Run Code Online (Sandbox Code Playgroud)
问题:
var app = require('../');
将无法在此群集环境中工作.它应该返回哪个工作者应用程序?它应该返回群集对象而不是Express应用程序吗?我能想到的唯一解决方案是有条件地关闭群集功能,如果从测试脚本(if (module.parent.parent) ...
)请求应用程序,则只运行一个应用程序.
用Mocha测试集群Express应用程序的任何其他方法?
我发布这个问题已经有很长一段时间了.由于没有人回答,我将自己回答这个问题.
我按原样保留了/index.js:
module.exports = process.env.CODE_COV
? require('./lib-cov/app')
: require('./lib/app');
Run Code Online (Sandbox Code Playgroud)
在启动集群的/lib/app.js中,我有以下代码.简而言之,我只在非测试环境中启动集群.在测试环境中,群集未启动,但只有一个应用程序/工作程序本身按cluster.isMaster && !module.parent.parent
条件中的定义启动.
var cluster = require('cluster'),
express = require('express'),
app = module.exports = express.createServer();
if (cluster.isMaster && !module.parent.parent) {
// Considering I have 4 cores.
for (var i = 0; i < 4; ++i) {
cluster.fork();
}
} else {
// do app configurations, then...
// Don't listen to this port if the app is required from a test script.
if (!module.parent.parent) {
app.listen(8080);
}
}
Run Code Online (Sandbox Code Playgroud)
在上述情况下,!module.parent.parent
仅当应用程序未由测试脚本启动时,才会将其评估为真实对象.
module
是当前的/lib/app.js脚本.module.parent
是它的父/index.js脚本.module.parent.parent
是undefined
如果应用程序通过直接启动node index.js
.module.parent.parent
如果应用程序是通过其中一个脚本启动的,则是测试脚本.因此,我可以安全地启动脚本,我可以设置自定义端口.
/test/test1.js
var app = require('../');
app.listen(7777);
// send requests to app, then assert the response.
Run Code Online (Sandbox Code Playgroud)
同时,如果我需要实际运行应用程序,即不进行测试,那么我运行node index.js
它将启动应用程序集群.
归档时间: |
|
查看次数: |
2822 次 |
最近记录: |