Sometimes, we want to load vanilla JavaScript libraries into Node.js.
in this article, we’ll look at how to load vanilla JavaScript libraries into Node.js.
How to load vanilla JavaScript libraries into Node.js?
To load vanilla JavaScript libraries into Node.js, we can use readFileSync
to read the JavaScript file.
Then we call the runInNewContext
method from the vm
module to run the script in a new context.
For instance, we write
execfile.js
const vm = require("vm");
const fs = require("fs");
module.exports = (path, context = {}) => {
const data = fs.readFileSync(path);
vm.runInNewContext(data, context, path);
return context;
}
to create the execfile.js module, which exports a function that calls readFileSync
with the script path
.
Then we call vm.runInNextContext
with the data
, context
, and path
to run the script in the given context
.
And then we return the context
.
Then we require execfile.js in another module and call the exported function with
app.js
const execfile = require("./execfile");
const context = execfile("example.js", {
someGlobal: 42
});
context.getSomeGlobal()
We call execfile
with the 'example.js'
and a context object that incorporate into the returned context.
And then we call context.getSomeGlobalto run the global function in the
example.js` script.
Conclusion
To load vanilla JavaScript libraries into Node.js, we can use readFileSync
to read the JavaScript file.
Then we call the runInNewContext
method from the vm
module to run the script in a new context.