Recently I came across a tweet by Ingvar Stepanyan. He shared the --check
flag for executing JavaScript files in Node.js. I didn't know about this option.
$ node --check some.js
$ node --check some-invalid.js
/Users/stefanjudis/test.js:3
});
^
SyntaxError: Unexpected token }
at checkScriptSyntax (bootstrap_node.js:457:5)
at startup (bootstrap_node.js:153:11)
at bootstrap_node.js:575:3
What --check
enables is a quick check for syntax errors of a JavaScript file without actually executing it. This can be very handy when you're transforming code and just want to make sure the transformation result is valid JavaScript.
On that note: I came accross the vm module which was mentioned in the replies to the tweet. The vm
module is part of Node core and you can use it to evaluate/execute JavaScript in a sandboxed environment which you control, too.
So far I didn't need this module but you can use it to evaluate and syntax check JavaScript files from within your scripts.
const vm = require('vm');
const script = new vm.Script('var a =');
The constructor of vm.Script
throws an exceptions if there are any syntax errors.
This module looks quite interesting. So, if you're dealing with generated code you might want to check it out. ;)