我正在用 node.js 编写一个脚本,该脚本在启动时会迅速耗尽内存。
要解决这个问题,我必须将内存增加到>>5GB。我知道通过命令行增加内存限制是必要的,以这种方式启动脚本:node max-old-space-size= script.js,效果很好。
我的问题是,如何从代码中设置 max-old-space-size ?可以从代码中设置变量,因此运行脚本的人可以在命令行中省略 max-old-space-size= 吗?
我想要获得的是,下载我的脚本的用户启动它,并且无需设置任何内容,该脚本就可以使用我从代码中设置的内存大小。
感谢您的帮助!
最佳答案
实现您想要的效果的一种方法是从脚本中重新生成 Node 。我不确定这是否是最好的方法,但它应该有效。
# cat test.js
var cp = require('child_process');
function main() {
console.log('This is the main script');
}
function spawn() {
console.log('spawning the script with the correct node arguments');
var c = cp.spawn('/opt/local/bin/node', ['--max-old-space-size=5120', __filename], {
'stdio': 'inherit',
'env': {
'RUN_MAIN_SCRIPT': 'TRUE'
}
});
c.on('error', function (e) {
console.log('Error');
console.log(e.toString());
});
}
process.env['RUN_MAIN_SCRIPT'] ? main() : spawn();
# node test.js
spawning the script with the correct node arguments
This is the main script
#
关于javascript - 从javascript代码设置堆内存大小?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54186636/