This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
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.
How to check JavaScript syntax from the command line
Section titled How to check JavaScript syntax from the command lineLet's have a look at Node.js' --check
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
The --check
option turns the Node.js binary into a JavaScript syntax checker that parses the passed source code and looks for invalid syntax. Node.js is not running any code in this "check mode".
The documentation of the check
parameter states the following:
Check the script's syntax without executing it. Exits with an error code if script is invalid.
A quick syntax check like that can be convenient if you're transforming code and want to make sure that your code transformation generated valid JavaScript.
How to check JavaScript syntax from within JavaScript
Section titled How to check JavaScript syntax from within JavaScriptWhile looking into the --check
option, I also learned about the vm module. The vm
module is part of Node.js core, and you can use it to evaluate/execute JavaScript in a sandboxed environment under your control, too.
You can use it to evaluate and syntax check JavaScript files from within your scripts. Check JavaScript with JavaScript, so to say. ?
const vm = require('vm');
const script = new vm.Script('var a =');
The constructor of vm.Script
throws an exceptions if there are any syntactial errors in the provided JavaScript code string.
The vm
module looks quite interesting. If you're generating code, you might want to include and build your own JavaScript syntax checker. ;)
Reply to Stefan
This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
Stefan Judis | Sciencx (2017-10-03T22:00:00+00:00) How to quickly perform a syntax check of a JavaScript file (#tilPost). Retrieved from https://www.scien.cx/2017/10/03/how-to-quickly-perform-a-syntax-check-of-a-javascript-file-tilpost/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.