Published at
Updated at
Reading time

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.

$ node --check some.js

$ node --check some-invalid.js
SyntaxError: Unexpected token }
  at checkScriptSyntax (bootstrap_node.js:457:5)
  at startup (bootstrap_node.js:153:11)
  at bootstrap_node.js:575:3

--check turns the Node.js binary into a syntax checker looking for errors in a JavaScript file. Node.js is not running any code in "check mode". This functionality can be very handy if 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 under your 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 syntactial errors.

This module looks quite interesting. If you're generating code you might want to include your own JavaScript syntax checker. ;)

Related Topics

Related Articles