javascript - 从javascript代码设置堆内存大小?

标签 javascript node.js environment-variables heap-memory

我正在用 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/

相关文章:

visual-c++ - 如何使用 CMake 在 Visual Studio 2017 RC1 中设置环境变量?

python - 在Windows 10 cmd中切换不同的Python版本

javascript - 提交 POST AngularJS 后表单未清除

javascript - 根据浏览器的宽度调整 div 的宽度

node.js - Electron 错误错误: Cannot find module 'mysql' Require stack:

java - 环境变量未确认

javascript - 异步Javascript : Unexpected result

javascript - Sencha 现代应用程序 View Controller 未绑定(bind)被调用?

javascript - 在 Windows 10 上重新运行 Node.js 服务器时出现 EADDRINUSE 错误

node.js - Azure Web 应用程序意外 "Bad Request"