How do you import non-node.js files?

javascript, node.js

Solution

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`

Problem

How do I load 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?

Original source