Run JSLint on a .js file from debugging console in chrome or firefox

孤人 提交于 2019-11-30 13:59:44
Cracker

You can run JSLint on JavaScript code using the below syntax:

var code = "var a = 1 + 2;";
JSLINT(code);

And you can print the syntax tree as you have mentioned in the question.

Now in your case, you need to read the JavaScript source from JavaScript files. You can make an AJAX call to read the source code of the JavaScript file into a variable. Then make a call to JSLINT as above passing that variable. A sample using jQuery would be like below.

$(function() {
    // Include jslint.js
    $('<script src="http://localhost/yourapp/jslint.js">').appendTo("head");

    // Read JavaScript file contents into 'code'
    $.get('http://localhost/yourapp/somescript.js', function(code) {

        // Run JSLINT over code
            JSLINT(code);

        // Print the parse tree
        console.log(JSON.stringify(JSLINT.tree, [
                    'string',  'arity', 'name',  'first',
                    'second', 'third', 'block', 'else'
                    ], 4));
        });
});

Depending on what you are trying to achieve, a standalone JavaScript console (eg. NodeJS) would be a better alternative than a browser console. I guess there exist Node packages for JSLint. But if you want to include it manually you can simply do it as below.

First add the below line at the end of jslint.js

exports.JSLINT = JSLINT;

Then write your code in say mycode.js.

var fs = require("fs");
var jslint = require("./jslint.js");

fs.readFile("./test.js", function(err, code) {
    var source = code.toString('ascii');    

    jslint.JSLINT(source);

    console.log(JSON.stringify(jslint.JSLINT.tree, [
         'string',  'arity', 'name',  'first',
         'second', 'third', 'block', 'else'
        ], 4));
},"text");

Then run your code from console as:

node mycode.js
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!