开发者

How do you import non-node.js files?

How do I load开发者_JAVA百科 external js files that don't fit the node.js format. I am trying to import the json serialize library. How can I do this?


2 answers...

1) the JSON object is built-in to node.js, so you can just call JSON.parse() and JSON.stringify(), there is no need to import external code for this particular case.

2) to import external code, node.js follows the CommonJS module specification and you can use require()

so if you have a file called external.js (in the same directory as the rest of your code):

this.hi = function(x){ console.log("hi " + x); }

and from node you do:

var foo = require("./external");
foo.hi("there");

you will see the output hi there


If you trust the code (I mean, really trust the code) then you can eval it:

eval(require('fs').readFileSync('somefile.js', 'utf8')); 

I wouldn't recommend doing this with remote code (because it could change without your knowledge) but if you have a local copy of something then it should be fine.


Write wrappers or change the code.

What should automagically make it work? How's Node supposed to know which functions should get exported or not?

All you can do is to adjust the code to match the Common JS standard, but before you do that, check the API Docs and the Modules Pages on the Node.js Wiki, to see whether someone already did the job for you :)

If you write code yourself that should work in a Browser and Node.js you can use a wrapper like the following one:

(function(node) {
    // Your Awesome code here
    if (node) {
        exports.foo = ...

    } else {
        window.foo = ...
    }

})((function(){return ('' + this).slice(8, -1) !== 'DOMWindow';})());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜