I have created a node.js application. I need to compile or do a check whether syntax error occurs before running the node.js service.I need to integrate this in jenkins. Kindly guide me to validate the node.js application
Look into TypeScript. It is a language which allows you to get autocomplete with types and fails compilation if you have some syntax errors. It is a superset of JavaScript and transpiles to JavaScript.
Node.js provides CLI option --check
or -c
for checking a given file for syntax errors without running it. When working with Linux or MacOS a command like the following one helps with checking all obvious javascript files in a folder for containing basically working code:
find -name "*.js" | xargs node -c
You can use 'node-syntax-error' module. it helps you to detect and report syntax errors in source code strings.
When you type node src.js you get a friendly error report about exactly where the syntax error is. This module lets you check for syntax errors and report them in a similarly friendly format that wrapping a try/catch around Function() or vm.runInNewContext() doesn't get you.
For example:
var fs = require('fs');
var check = require('syntax-error');
var file = __dirname + '/src.js';
var src = fs.readFileSync(file);
var err = check(src, file);
if (err) {
console.error('ERROR DETECTED' + Array(62).join('!'));
console.error(err);
console.error(Array(76).join('-'));
}
Use the following code for checking syntax error in node.js application -
var check = require('syntax-error')
Check the source code string src for syntax errors. Optionally you can specify a filename file that will show up in the output. If src has a syntax error, return an error object err that can be printed or stringified. If there are no syntax errors in src, return undefined.
var err = check(src, file)
Using
node --check
Only finds very grave errors and can be tricky to execute.
I would suggest to use a linter like 'eslint'. Because:
using eslint
package https://www.npmjs.com/package/eslint It's a very common library to check the syntax of any JS/TS framework
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.