Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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" "$@"

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...