How to quickly perform a syntax check of a JavaScript file
- Published at
- Updated at
- Reading time
- 2min
I found a tweet from Ingvar Stepanyan in which he shared that Node.js offers a way to check if a JavaScript file is syntactically valid.
That's news to me! Let's have a look.
Node.js' --check
option is available when running a JavaScript file.
$ 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 command line flag turns the Node.js binary into a JavaScript syntax checker that parses 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.
While 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.
Yes, that's right, 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 =');
// evalmachine.<anonymous>:1
// var a =
//
// SyntaxError: Unexpected end of input
// at new Script (node:vm:100:7)
The constructor of vm
throws an exception if there are any syntactical errors in the provided JavaScript code string.
--check
and the vm
module look quite interesting! So, if you're generating or transforming code, include and build your own JavaScript syntax checker with them. Have fun! ;)
Join 5.5k readers and learn something new every week with Web Weekly.