如何修复“在索引 0 处找到带有非文字参数的 fs.readFile”?

Hon*_*iao 6 node.js eslint typescript2.0 typescript-eslint

我正在尝试在 TypeScript 项目中添加eslint-plugin-security 。然而,对于这些代码

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);
Run Code Online (Sandbox Code Playgroud)

我收到了很多这样的 ESLint 警告:

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
Run Code Online (Sandbox Code Playgroud)

我在https://github.com/nodesecurity/eslint-plugin-security#detect-non-literal-fs-filename找到了有关此 ESLint 错误的文档

但我仍然不知道如何解决它。任何指南都会有帮助!谢谢


更新

发现只要使用传递path.joinor返回的路径path.resolve就会显示这个 ESLint 问题。

如果我更改为绝对路径,ESLint 问题就消失了。path.join然而,这失去了相对路径 by或的好处path.resolve

fs.readFileSync('/Users/me/project/ssl.key');
Run Code Online (Sandbox Code Playgroud)

寻找替代/更好的方法(如果存在)。

(可能是误报?在https://github.com/nodesecurity/eslint-plugin-security/issues/65询问)

Jos*_*osh 0

是的,这是一场虚惊。它已在https://github.com/eslint-community/eslint-plugin-security/pull/109中修复,并eslint-plugin-security@1.7.1根据项目的变更日志发布。