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!");
    > 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: