How do I load my script into the node.js REPL?

前端 未结 11 1613
执念已碎
执念已碎 2020-11-30 17:59

I have a script foo.js that contains some functions I want to play with in the REPL.

Is there a way to have node execute my script and then jump into a

11条回答
  •  独厮守ぢ
    2020-11-30 18:13

    replpad is cool, but for a quick and easy way to load a file into node, import its variables and start a repl, you can add the following code to the end of your .js file

    if (require.main === module){
        (function() {
            var _context = require('repl').start({prompt: '$> '}).context;
            var scope = require('lexical-scope')(require('fs').readFileSync(__filename));
            for (var name in scope.locals[''] )
                _context[scope.locals[''][name]] = eval(scope.locals[''][name]);
            for (name in scope.globals.exported)
                _context[scope.globals.exported[name]] = eval(scope.globals.exported[name]);
        })();
    }
    

    Now if your file is src.js, running node src.js will start node, load the file, start a REPL, and copy all the objects declared as var at the top level as well as any exported globals. The if (require.main === module) ensures that this code will not be executed if src.js is included through a require statement. I fact, you can add any code you want to be excuted when you are running src.js standalone for debugging purposes inside the if statement.

提交回复
热议问题