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

node.js

Solution

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');

Problem

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`. Why`foo` 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; }); } }()); ```

Original source