Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you import non-node.js files?

Tags:

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?

like image 438
Will03uk Avatar asked Jan 11 '11 21:01

Will03uk


People also ask

Can we import a file in js?

An ES6 module is a JavaScript file that can import and export code. It automatically uses the strict mode. The ES6 module system and Node JS require are the most popular ways of including a JS file in another JS file.

How do I import and require node JS?

If you want to use require module then you have to save file with '. js' extension. If you want to use import module then you have to save file with '. mjs' extension.

How do I include an external js file in another JavaScript file?

To include an external JavaScript file, we can use the script tag with the attribute src . You've already used the src attribute when using images. The value for the src attribute should be the path to your JavaScript file.


2 Answers

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

like image 167
nicolaskruchten Avatar answered Sep 28 '22 04:09

nicolaskruchten


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.

like image 45
RandomEtc Avatar answered Sep 28 '22 03:09

RandomEtc