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

Categories

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

javascript - execute some code and then go into interactive node

Is there a way to execute some code (in a file or from a string, doesn't really matter) before dropping into interactive mode in node.js?

For example, if I create a script __preamble__.js which contains:

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

and a user types node __preamble__.js they get this output:

preamble executed! poor guy!
> [interactive mode]
See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...