Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

node.js

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;
        });
    }
}());
like image 404
gremo Avatar asked Feb 16 '13 18:02

gremo


People also ask

How do I include another file in node JS?

To include functions defined in another file in Node. js, we need to import the module. we will use the require keyword at the top of the file. The result of require is then stored in a variable which is used to invoke the functions using the dot notation.

Which module is not a built in module in node JS?

Explanation: The fsread modules is not a built-in node module in Node. js.

How can you make properties and method available outside the module file in node JS?

35) Which of the following keyword is used to make properties and methods available outside the module file? Answer: C is the correct option. The exports keyword is used to make properties and methods available outside the module file.


1 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');
like image 166
loganfsmyth Avatar answered Oct 12 '22 12:10

loganfsmyth