Load Vanilla Javascript Libraries into Node.js
There is a much better method than using eval
: the vm
module.
For example, here is my execfile
module, which evaluates the script at path
in either context
or the global context:
var vm = require("vm");
var fs = require("fs");
module.exports = function(path, context) {
context = context || {};
var data = fs.readFileSync(path);
vm.runInNewContext(data, context, path);
return context;
}
And it can be used like this:> var execfile = require("execfile");
> // `someGlobal` will be a global variable while the script runs
> var context = execfile("example.js", { someGlobal: 42 });
> // And `getSomeGlobal` defined in the script is available on `context`:
> context.getSomeGlobal()
42
> context.someGlobal = 16
> context.getSomeGlobal()
16
Where example.js
contains:function getSomeGlobal() {
return someGlobal;
}
The big advantage of this method is that you've got complete control over the global variables in the executed script: you can pass in custom globals (via context
), and all the globals created by the script will be added to context
. Debugging is also easier because syntax errors and the like will be reported with the correct file name. How to import nodejs modules in vanilla Javascript file
These modules are packaged using a tool called npm. You can use module loaders or bundlers like Browserify or Webpack to use npm modules in the frontend.
This might help you
Load “Vanilla” Javascript Libraries into Node.js = 'Unexpected token export'
The error 'Unexpected token export' is caused because the library is using
export default thingToExport;
instead of
module.exports = thingToExport
This is an ES6 feature not supported by Node (yet), so when Node tries to run the code, it throws an error.
How to solve: try modifying the last line of the library so it says module.exports = rsa;
.
I should add, though, that eval
is not a good way to load a library into your own code. That is what require
is for. If you have installed this library with npm i
and it is in your node_modules, you should be able to load it into your code with var rsa = require('rsa');
.
Again though, if you're not transpiling the code, it may have problems with export default
, so you will probably want to change that to module.exports
either way.
New to node.js; need help importing an npm module into my front-end vanilla JS project
Import and Export are features from ECMAScript 6 (http://es6-features.org/#ValueExportImport), so i guess you are not using any Javascript compiler ( Babel for example https://babeljs.io/docs/en/ ).
But, if you don't want use any compiler you can simple change the code to import the library like this:
var asdfjkl = require('asdfjkl');
How to use external JS library methods in my Node.JS project if this library does not exist in NPM
If your library have a
package.json
: You can install the package directly from the git repository, for examplenpm install https://github.com/vendor-creator/vendor-package
. NOTE that for this method to work, in cases where the module has to be built, the git repository should contain adist/
folder containing the built code or have in itspackage.json
, aprepare
step responsible for building the package upon installation.If your library does not have a
package.json
and is simply a vanilla JavaScript file like the Lodash JavaScript file, I would advise just like in the post you linked, to create avendor.js
file (.min
if the script is minified), copy and paste the content of the file andrequire
it. Be aware that some libraries using CDN and not NPM, are designed for browser environment and may lack CommonJS support preventing you from usingrequire
. In that case you'll have to modify the library source code.If it's a small library, there is no need to create an advanced build system. If the library is stable, just copy and paste it and you'll be fine. When in doubt always follow the K.I.S.S principle.
Related Topics
Why Do Empty JavaScript Arrays Evaluate to True in Conditional Structures
Jquery: Change Event to Input File on Ie
Passing a PHP Variable to JavaScript in a Blade Template
How to Write Regex to Validate Dates
Options for Testing Service Workers via Http
Execute an Exe File Using Node.Js
Why Does This Foreach Return Undefined When Using a Return Statement
JavaScript Property with Three Dots (...)
Why Does a Simple .*? Non-Greedy Regex Greedily Include Additional Characters Before a Match
How to Create a Date Object from String in JavaScript
Angularjs Routing 404 Error with HTML5 Mode
JavaScript Settimeout and Loops
Convert Unix Timestamp to Date Time (Javascript)
D3.JSON Method Doesn't Return My Data Array
Onclick Event Binding in React.Js
JavaScript "Variable Variables": How to Assign Variable Based on Another Variable
Quickest Way to Pass Data to a Popup Window I Created Using Window.Open()