javascriptjshint

Use JSHint in python


I have bunch of JavaScript functions, all loaded in memory and I need to validate their syntax before I write them down in .js files.

The code that I have is in python and need to check the validity of js functions on the fly. So, looking for a python package that could perform this task for me.

JSHint works OK if I write each function in a file and then call something like os.system("jshint --verbose sample.js"), but writing the js functions in file is expensive and takes a lot of time.

I was wondering if there is any way that I could call JSHint directly in python.

In addition, I can get what I need if it was possible to call JSHint in command line directly with the code, not its address. In other words, if I could pass the actual script jshint "var source = ['function goo() {}', 'foo = 3;' ];", instead of its address like jshint sample.js, I could get what I need.


Solution

  • You should be piping the input to whatever linter you decide to use.

    See this answer on piping input to another program from Python.

    Regarding your specific use case, JSHint reads from stdin when the filename passed is '-'

    The following should work:

    import subprocess
    code = "function goo() {}"
    result = subprocess.run("jshint --verbose -".split(), capture_output=True, text=True, input=code).stdout