简体   繁体   中英

Import a Javascript file into a REPL session

I'm on Windows 10 TP build 9926, using nodejs. I want to be able to import a Javascript into a current session of nodejs that is running on Windows command prompt so that functions from the imported script can be called from within the REPL. How can I achieve that? My attempt of "import" and "require" did not succeed.

I tried the following in a nodejs session running from the directory that has the "learn.js" javascript;

var n = require("learn.js")

Then got the following error message:

Error: Cannot find module 'learn.js'
    at Function.Module._resolveFilename (module.js:336:15)
    at Function.Module._load (module.js:278:25)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at repl:1:9
    at REPLServer.defaultEval (repl.js:132:27)
    at bound (domain.js:254:14)
    at REPLServer.runBound [as eval] (domain.js:267:12)
    at REPLServer.<anonymous> (repl.js:279:12)
    at REPLServer.emit (events.js:107:17)

The learn.js file needs to look like the following:

"use strict";

module.exports.myfunc1 = function() {
    console.log("Hi there.");
}

module.exports.myfunc2 = function() {
    console.log("Goodbye.");
}

Also, you must require it like this:

var n = require('./learn.js');

or

var n = require('./learn');

You must make the path relative to where you are running the REPL. Node won't automatically check the local directory.

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