0

I have a JavaScript file which is not written for Node.js. It is actually written by me, but this question may be more understandable if you think of it as a third-party library.

Normally, a Node.js module only exposes the module.exports object to external code. This requires the file to be written with Node.js in mind.

However, the file isn't written for Node.js, yet I want to include it into a Node.js module. I can't edit this file, since it will be used later, independently of Node.js.

I imagine I could pull it off by reading the file and calling eval on the contents, but is there a better way?

TL;DR

How can I include a .js file into a Node.js module, without rewriting it to use Node.js-specific code like exports?

P.S. The reason I want to use it in Node.js is for a few tests before it's deployed elsewhere.

1 Answer 1

2

It depends on how the code is written on that file. If the file contains a class or a single object then you can do this:

(function(global) {

    function MyClass() {


    }

    MyClass.prototype = {
            ...
    };

    if( typeof module !== "undefined" && module.exports ) {
        module.exports = MyClass;
    }
    else if ( global ) {
        global.MyClass = MyClass;
    }

})(this);

You can modify the global assignment to be a deeper namespace instead if required.

Sign up to request clarification or add additional context in comments.

7 Comments

This is the standard way I see in github projects for files that should work in browser as well as node.js.
What about for files that should work in other interpreters, like WScript?
@KendallFrey then it will attach it to the global object in that environment. Unless it supports module.exports, of course.
global is undefined in WScript. I would like this to be available in WScript, so how can I provide compatibility?
@KendallFrey global is locally scoped custom variable I created in that function (it might as well be asdasd since it's local), it's passed in the last line this which will evaluate to the global object. After that function has executed, you can access it with this.MyClass when in global context. You can also use any other global object reference that is available in that environment (window, self, etc in browsers), but this keyword is specified to resolve to the global object when in global scope.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.