Retrieves the ESLint-generated SourceCode object of a file from its absolute path.
npm install get-sourcecode-from-file-pathAnother utility that I am bound to reuse between open-source projects. (I'll consider making a package combining my shared utilities in due time.) Here is the code with JSDoc comments:
``jsSourceCode
/**
* Gets the ESLint-generated object of a file from its absolute path.SourceCode
* @param {string} absolutePath The absolute path of the file.
* @param {Object} [options] The additional options as follows:
* @param {import('eslint').Linter} [options.linter] The Linter instance used to retrieve the object, defaulting to a new Linter() per operation, ensuring each instance of the function is based on its own linter (just in case somehow some linters were to run concurrently).languageOptions
* @param {import('eslint').Linter.LanguageOptions} [options.languageOptions] The object used by linter.verify(), defaulting to a version that is TypeScript- and JSX-compatible.SourceCode
* @returns The ESLint-generated object of the file, from which the AST (sourceCode.ast) and all comments (sourceCode.getAllComments()) can be extracted. null when encountering fatal syntax.
*/
export const getSourceCodeFromFilePath = (
absolutePath,
{ languageOptions = typeScriptAndJSXCompatible, linter = new Linter() } = {}
) => {
// the raw code of the file at the end of the absolute path
const text = fs.readFileSync(absolutePath, "utf8");
// utilizes linter.verify ...
linter.verify(text, { languageOptions });
// ... to retrieve the raw code as a SourceCode object
const sourceCode = linter.getSourceCode();
if (!sourceCode) return null;
else return sourceCode;
};
``