Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

node.js - How to set nodejs interpreter arguments from javascript source

I have someScript.js which requires some node options for correct running. E.g. (let's suppose we have node 0.12.7):

node --harmony someScript.js

I wish to run it without --harmony option and somehow set it inside the script.

I tried to change process.execArgv:

process.execArgv.push('--harmony');

function getGenerator() {
    return function *() {
        yield 1;
    };
}

var gen = getGenerator();

Since NodeJS is interpreter it could allow such settings change (even on the fly). But, NodeJS seems to ignore process.execArgv changes.

Also I tried v8.setFlagsFromString:

Interesting, all NodeJs versions which needed --harmony to support generators do not contain v8 module. So, I made experiments with NodeJS 4.1.1

var v8 = require('v8');
var vm = require('vm');

v8.setFlagsFromString('--harmony');

var str1 =
    'function test1(a, ...args) {' +
    '  console.log(args);' +
    '};';

var str2 =
    'function test2(a, ...args) {' +
    '  console.log(args);' +
    '};';

eval(str1);
test1('a', 'b', 'c');

vm.runInThisContext(str2);
test2('a', 'b', 'c');

Unfortunately, v8.setFlagsFromString('--harmony') did not help, even for eval() and vm.runInThisContext().

I wish to avoid creating some wrapping script.

So, is there some other way to set nodejs arguments from javascript source?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If one will have such someScript.js:

#!/bin/sh
":" //# comment; exec /usr/bin/env node --harmony "$0" "$@"

function test(a, ...args) {
    console.log(args);
}

test('a', 'b', 'c');

Then "sh someScript.js" command will use interpreter and arguments specified in the someScript.js.

If one will mark someScript.js executable (chmod u+x someScript.js). Then ./someScript.js command also will work.

This article was helpful: http://sambal.org/2014/02/passing-options-node-shebang-line/

Also if you use Windows EOL there will be a bug with ' ' adding to last script argument. If there are no arguments there will be one (' ').

UPDATE:

Some shells allow to use

#! /usr/bin/env node --harmony

instead of

#!/bin/sh
":" //# comment; exec /usr/bin/env node --harmony "$0" "$@"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...