Home » Nodejs » How to include a file which is not a module in Node.js (to make a module of it)?

How to include a file which is not a module in Node.js (to make a module of it)?

Posted by: admin January 30, 2018 Leave a comment

Questions:

Purpose: making a Node.js module or a Requirejs AMD module, from a plain old JavaScript file like this:

var foo = function () {};

I have no control and I can’t edit foo.js.

Whyfoo is is a plain empty object inside the first if? How can I “include” a plain JavaScript file in my module? File mymodule.js:

(function(root) {
    if(typeof exports === 'object') { // Node.js
        var foo = require('./foo');

        console.log(foo); // { }
    } else if (typeof define === 'function' && define.amd) { // RequireJS AMD
        define(['foo'], function () {
            return foo;
        });
    }
}());
Answers:

Node modules loaded with require must populate an exports object with everything that the module wants to make public. In your case, when you require the file nothing is added to exports, hence it shows up as empty. So the short answer is that you need to modify the contents of foo.js somehow. If you can’t do it manually, then you need to do it programmatically. Why do you have no control over it?

The easiest being that you programmatically wrap the contents if foo.js in the code needed to make it a proper module.

// Add an 'exports' line to the end of the module before loading it.
var originalFoo = fs.readFileSync('./foo.js', 'utf8');
fs.writeFileSync('./foo-module.js', originalFoo + "\nexports.foo = foo;");
var foo = require('./foo-module.js');

Questions:
Answers:

You Could Try:

var fs = require('fs');

var foo = fs.readFileSync('foo.js', 'utf8') // Or request it somehow, just get it as a string

foo += "module.exports.foo = module.exports = foo;";

fs.writeFileSync('fooModule.js',foo);

var foo = require('./fooModule');

// foo() and foo.foo() are both the same

Note: This requires node.