Black lives matter
Portrait Dr. Axel Rauschmayer
Dr. Axel Rauschmayer
Homepage | Twitter
Cover of book “JavaScript for impatient programmers”
Book, exercises, quizzes
(free to read online)
Cover of book “Deep JavaScript”
Book (50% free online)
Cover of book “Tackling TypeScript”
Book (first part free online)
Logo of newsletter “ES.next news”
Newsletter (free)

Tip: load source from a file in the Node.js shell

[2011-05-18] dev, nodejs, repl, javascript, jslang
(Ad, please don’t block)

Node.js is really handy as an interactive shell for JavaScript. To load source code from a file, you must create a module. This post explains how.

File test.js:

    exports.foo = function() {
        console.log("Hello world!");
    };
Interaction:
    > var t = require("./test");
    > t.foo()
    Hello world!
Node caches modules. Thus, if the source file changes, you need to clear the module cache and re-require the module:
    > require.cache = {};
    > t = require("./test");
Related blog post: