child_process.fork()允许一个模块生成具有指定环境变量的新节点环境。这两个进程可以通过 相互发送消息send()
,并通过“消息”事件接收这些消息。
例如,如果您当前的主模块名为server.js
,那么您可以start.js
在同一目录中添加一个临时模块(将是新的 lambda 函数),如下所示:
// Add NODE_DEBUG to this process's environment variables, which are passed by default to
// the forked node environment.
process.env.NODE_DEBUG = 'https';
const cp = require('child_process');
const n = cp.fork('server.js');
// Cached callback functions, in case client can pass in different callbacks.
// Use an object instead of array, to avoid memory leaks.
const cbs = {};
var cbIndexCounter = 0; // To make callback indices unique
// Call appropriate callback with response from child process, and delete cached callback.
n.on('message', (m) => {
cbs[m.cbIndex](m.error, m.result);
delete cbs[m.cbIndex];
});
n.on('error', (err) => {
console.log('Child node env error: ', err);
});
// Cache the callback; forward event, context, index to child process; and increment index.
exports.myHandler = function(event, context, callback) {
cbs[cbIndexCounter] = callback;
n.send({
event: event,
context: context,
cbIndex: cbIndexCounter++
});
}
server.js
可以通过添加“消息”事件侦听器来稍微修改该模块:
process.on('message', (m) => {
exports.myHandler(m.event, m.context, function(error, result) {
process.send({
error: error,
result: result,
cbIndex: m.cbIndex
});
});
});
// The rest of your original code ...
exports.myHandler = function (event, context, callback) {
// Whatever you need here...
}