Last Updated: May 15, 2019
·
54.54K
· calamari

How to use jslint in node.js projects properly

Javascript is a highly dynamic language and there is no doubt about having a control mechanism like JSLint that prevents you from writing really stupid code in the first place.

But when writing node.js code, you probably get a lot of false positive problems counted, if you JSLint your code. Most probably they are all about require is not defined or module is nor defined. To declare those as ok it might be tempting to just add those objects which are defined by node.js to a directive at the top of your node.js program file. Something like:

/*global require, module,  __dirname */

But there is an easier, and more semantical way to do just that. Simply put the following JSLint option

/*jslint node: true */

at the top of your files instead, and all magical objects that can be used by node.js will no longer be marked as problems. Plus, if you do it like this, it is saying to the jslinter that it handles a node.js program, so if you also (and you should) put in a "use strict"; statement, it will not be marked as something that has to be put in a function.

So this tend to be a good starting point for every node.js file:

/*jslint node: true */
"use strict";

7 Responses
Add your response

I've found that the best way to lint .js files is directly in Sublime Text 2.

over 1 year ago ·

Yes, and there it is essential, that you only see problems, that really are problems, else you are either distracted due to many false problems or you simply start ignoring them. It's like failing tests.

over 1 year ago ·

If you're using Intelliji WebStorm, you can set this option in JSHint options, section called "Environmnent"

over 1 year ago ·

There shouldn't be a space after the first asterisk:
/*jslint node: true */

over 1 year ago ·

Yes, you're right. There was a typo in the second jslint comment. I fixed it.

Thanks,

over 1 year ago ·

very helpful, thanks

over 1 year ago ·

Great tip, can even be automated by Grunt!:

BEFORE
javascript jshint: { ignore_warning: { options: { '-W117': true, // ignores ‘require is not defined’ error '-W097': true, // allows non-function form of ‘use strict’ }, src: [‘src/**/*.js’] }, },

AFTER*
javascript jshint: { src: ['src/**/*.js'], options: { node: true } // enables error-free use of 'require' and 'use strict' keywords },

**This implementation is especially great for larger codebases that need to be auto-linted just before being pushed into production.

Thanks!

over 1 year ago ·