UNPKG

js-error-finder

Version:

A utility to find syntax errors in JavaScript files.

44 lines (38 loc) 1.1 kB
const fs = require('fs'); const esprima = require('esprima'); /** * Finds errors in a JavaScript file. * * @param {string} filePath - The path to the JavaScript file to validate. * @returns {object} - An object containing `valid` (boolean) and `errors` (list of errors). */ function findJsErrors(filePath) { try { // Read the file const code = fs.readFileSync(filePath, 'utf-8'); // Parse the JavaScript code to find syntax errors esprima.parseScript(code, { tolerant: true }); return { valid: true, errors: [], }; } catch (e) { // If there's an error, extract details const errorMessage = e.message; const errorLine = e.lineNumber || 'Unknown line'; const errorColumn = e.column || 'Unknown column'; return { valid: false, errors: [ { message: errorMessage, line: errorLine, column: errorColumn, hint: `Error at line ${errorLine}, column ${errorColumn}.`, }, ], }; } } // Export the function for use in other files module.exports = findJsErrors;