执行一些代码,然后进入交互节点

在 node.js 中进入交互模式之前,是否有办法执行一些代码(在文件中或从字符串中,这并不重要) ?

例如,如果我创建一个脚本 __preamble__.js,其中包含:

console.log("preamble executed! poor guy!");

用户输入 node __preamble__.js就会得到如下输出:

preamble executed! poor guy!
> [interactive mode]
30737 次浏览

You can start a new repl in your Node software pretty easily:

var repl = require("repl");
var r = repl.start("node> ");
r.context.pause = pauseHTTP;
r.context.resume = resumeHTTP;

From within the REPL you can then call pause() or resume() and execute the functions pauseHTTP() and resumeHTTP() directly. Just assign whatever you want to expose to the REPL's context member.

There isn't a way do this natively. You can either enter the node interactive shell node or run a script you have node myScrpt.js. @sarnold is right, in that if you want that for your app, you will need to make it yourself, and using the repl toolkit is helpful for that kind of thing

Edit: Ignore this. @jaywalking101's answer is much better. Do that instead.

If you're running from inside a Bash shell (Linux, OS X, Cygwin), then

cat __preamble__.js - | node -i

will work. This also spews lots of noise from evaluating each line of preamble.js, but afterwords you land in an interactive shell in the context you want.

(The '-' to 'cat' just specifies "use standard input".)

Really old question but...

I was looking for something similar, I believe, and found out this. You can open the REPL (typing node on your terminal) and then load a file. Like this: .load ./script.js. Press enter and the file content will be executed. Now everything created (object, variable, function) in your script will be available.

For example:

// script.js
var y = {
name: 'obj',
status: true
};


var x = setInterval(function () {
console.log('As time goes by...');
}, 5000);

On the REPL:

//REPL
.load ./script.js

Now you type on the REPL and interact with the "living code". You can console.log(y) or clearInterval(x);

It will be a bit odd, cause "As time goes by..." keep showing up every five seconds (or so). But it will work!

I've recently started a project to create an advanced interactive shell for Node and associated languages like CoffeeScript. One of the features is loading a file or string in the context of the interpreter at startup which takes into account the loaded language.

http://danielgtaylor.github.com/nesh/

Examples:

# Load a string (Javascript)
nesh -e 'var hello = function (name) { return "Hello, " + name; };'


# Load a string (CoffeeScript)
nesh -c -e 'hello = (name) -> "Hello, #{name}"'


# Load a file (Javascript)
nesh -e hello.js


# Load a file (CoffeeScript)
nesh -c -e hello.coffee

Then in the interpreter you can access the hello function.

Similar answer to @slacktracer, but if you are fine using global in your script, you can simply require it instead of (learning and) using .load.

Example lib.js:

global.x = 123;

Example node session:

$ node
> require('./lib')
{}
> x
123

As a nice side-effect, you don't even have to do the var x = require('x'); 0 dance, as module.exports remains an empty object and thus the require result will not fill up your screen with the module's content.

Vorpal.js was built to do just this. It provides an API for building an interactive CLI in the context of your application.

It includes plugins, and one of these is Vorpal-REPL. This lets you type repl and this will drop you into a REPL within the context of your application.

Example to implement:

var vorpal = require('vorpal')();
var repl = require('vorpal-repl');
vorpal.use(repl).show();


// Now you do your custom code...


// If you want to automatically jump
// into REPl mode, just do this:
vorpal.exec('repl');

That's all!

Disclaimer: I wrote Vorpal.

nit-tool lets you load a node module into the repl interactive and have access to inner module environment (join context) for development purposes

npm install nit-tool -g

This can be achieved with the current version of NodeJS (5.9.1):

$ node -i -e "console.log('A message')"

The -e flag evaluates the string and the -i flag begins the interactive mode.

You can read more in the referenced pull request

node -r allows you to require a module when REPL starts up. NODE_PATH sets the module search path. So you can run something like this on your command line:

NODE_PATH=. node -r myscript.js

This should put you in a REPL with your script loaded.

First I tried

$ node --interactive foo.js

but it just runs foo.js, with no REPL.

If you're using export and import in your js, run npm init -y, then tell node that you're using modules with the "type": "module", line -

{
"name": "neomem",
"version": "1.0.0",
"description": "",
"type": "module",
"main": "home.js",
"keywords": [],
"author": "",
"license": "ISC"
}

Then you can run node and import a file with dynamic import -

$ node
Welcome to Node.js v18.1.0.
Type ".help" for more information.


> home = await import('./home.js')
[Module: null prototype] {
get: [AsyncFunction: get],
start: [AsyncFunction: start]
}


> home.get('hello')

Kind of a roundabout way of doing it - having a command line switch would be nice...