Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

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.

How to check JavaScript syntax from the command line

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.

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.

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.Script 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! ;)

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles