node.jseslinttypescript2.0typescript-eslint

How to fix "Found fs.readFile with non literal argument at index 0"?


I am trying to add eslint-plugin-security in a TypeScript project. However, for these codes

import { promises as fsp } from 'fs';
import fs from 'fs';
import path from 'path';

const index = await fsp.readFile(path.resolve(__dirname, './index.html'), 'utf-8');
const key = fs.readFileSync(path.join(__dirname, './ssl.key'));
await fsp.writeFile(path.resolve(__dirname, './sitemap.xml'), sitemap);

I got many these ESLint warnings:

warning Found fs.readFile with non literal argument at index 0   security/detect-non-literal-fs-filename
warning Found fs.readFileSync with non literal argument at index 0  security/detect-non-literal-fs-filename
warning Found fs.writeFile with non literal argument at index 0  security/detect-non-literal-fs-filename

I found the document about this ESLint error at https://github.com/nodesecurity/eslint-plugin-security#detect-non-literal-fs-filename

But I still have no idea how to fix it. Any guide will be helpful! Thanks


UPDATE:

Found out as long as using passing the path returned by path.join or path.resolve will show this ESLint issue.

If I change to absolute path, the ESLint issue is gone. However, this loose the benefit of the relative path by path.join or path.resolve.

fs.readFileSync('/Users/me/project/ssl.key');

Looking for an alternative / better way if exists.

(Might be a false alarm? Asked at https://github.com/nodesecurity/eslint-plugin-security/issues/65)


Solution

  • This was a false alarm, yes. It was fixed in https://github.com/eslint-community/eslint-plugin-security/pull/109 and released in eslint-plugin-security@1.7.1 per the project's changelog.