简体   繁体   中英

How can I access a variable declared in a javascript file in my node.js console?

How can I access variable values that are within a js file in my node console? How can I make that variable value available in my console?

For instance, let's say I have a file called file.js. This file only contains the following code:

const x = 10; 
const y = 5; 

How can I access the x and y values within my node console? For instance, let's say my node console is already open. How can I access these values so that I can run the following code in my node console...

> x + y

... and then be able to get a return value of 15?

You can put the contents of the script in an -e argument if you're using a decent shell and also pass -i to stay in the REPL. For example, sh:

$ node -e "$(cat file.js)" -i
> x + y
15

(Note that this runs the whole file like it's in the REPL, so it's different from, say, opening a debugger on node file.js .)

The equivalent when you already have the REPL open is to use .load , but it's noisy:

$ node
> .load file.js
const x = 10;
const y = 5;

undefined
> x + y
15

You should export your const s as described here:

module.exports.x = x;

and then, in your console do something like

const myModule = require(../file);
myModule.x + myModule.y

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM