Published at
Updated at
Reading time
2min

This post is part of my Today I learned series in which I share all my learnings regarding web development.

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 line

Let'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 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, 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. ;)

Related Topics

Related Articles