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?
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.
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.
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With