2

Building on related issue: Load "Vanilla" Javascript Libraries into Node.js

I'm trying to load a 'Vanilla' Javascript library 'rsa.js' into NodeJS, using the method described by Chris W. in the question above. In essence I've created a custom node_modules directory like this:

./node_modules/rsa/rsa-lib/rsa.js
./node_modules/rsa/rsa-lib/README
./node_modules/rsa/index.js

Only problem is, compiling the module fails on the last line of rsa.js:

undefined:836
export default rsa;
SyntaxError: Unexpected token export

rsa.js

var rsa = {};
 (function(rsa) {

   ...

})(rsa);
console.log("rsa",rsa);
export default rsa;

index.js

var fs = require('fs');

// Read and eval library
filedata = fs.readFileSync('./node_modules/rsa/rsa-lib/rsa.js','utf8');
eval(filedata);

/* The rsa.js file defines a class 'rsa' which is all we want to export */
exports.rsa = rsa

Any suggestions how to fix this problem?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Brilliant, swapping it for module.exports = rsa; did the trick. Also good point about the eval(), though not sure you can 'require' a vanilla javascript library...
You can require your own JS files using require('./path/to/file.js'), so I think you should be able to require someone else's javascript

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.