no-path-concat

禁止使用 __dirname__filename 进行字符串连接

Important

This rule was deprecated in ESLint v7.0.0. Please use the corresponding rule in eslint-plugin-n.

Learn more

在 Node.js 中,__dirname__filename 全局变量分别包含当前正在执行的脚本文件的目录路径和文件路径。有时,开发者会尝试使用这些变量来创建其他文件的路径,例如:

¥In Node.js, the __dirname and __filename global variables contain the directory path and the file path of the currently executing script file, respectively. Sometimes, developers try to use these variables to create paths to other files, such as:

var fullPath = __dirname + "/foo.js";

但是,这样做存在一些问题。首先,你无法确定脚本在什么类型的系统上运行。Node.js 可以在任何计算机上运行,​​包括 Windows,它使用不同的路径分隔符。因此,使用字符串连接并假设 Unix 样式的分隔符来创建无效路径非常容易。也有可能有双重分隔符,或者以无效路径结束。

¥However, there are a few problems with this. First, you can’t be sure what type of system the script is running on. Node.js can be run on any computer, including Windows, which uses a different path separator. It’s very easy, therefore, to create an invalid path using string concatenation and assuming Unix-style separators. There’s also the possibility of having double separators, or otherwise ending up with an invalid path.

为了避免混淆如何创建正确的路径,Node.js 提供了 path 模块。该模块使用系统特定的信息来始终返回正确的值。因此,你可以将前面的示例重写为:

¥In order to avoid any confusion as to how to create the correct path, Node.js provides the path module. This module uses system-specific information to always return the correct value. So you can rewrite the previous example as:

var fullPath = path.join(__dirname, "foo.js");

此示例不需要包含分隔符,因为 path.join() 会以最合适的方式执行此操作。或者,你可以使用 path.resolve() 检索完全限定的路径:

¥This example doesn’t need to include separators as path.join() will do it in the most appropriate manner. Alternately, you can use path.resolve() to retrieve the fully-qualified path:

var fullPath = path.resolve(__dirname, "foo.js");

无论在何处创建文件或目录路径,path.join()path.resolve() 都是字符串连接的合适替代品。

¥Both path.join() and path.resolve() are suitable replacements for string concatenation wherever file or directory paths are being created.

规则详情

¥Rule Details

此规则旨在防止 Node.js 中目录路径的字符串连接

¥This rule aims to prevent string concatenation of directory paths in Node.js

此规则的错误代码示例:

¥Examples of incorrect code for this rule:

在线运行
/*eslint no-path-concat: "error"*/

var fullPath = __dirname + "/foo.js";

var fullPath = __filename + "/foo.js";

此规则的正确代码示例:

¥Examples of correct code for this rule:

在线运行
/*eslint no-path-concat: "error"*/

var fullPath = dirname + "/foo.js";

何时不使用

¥When Not To Use It

如果你想允许路径名的字符串连接。

¥If you want to allow string concatenation of path names.

版本

此规则是在 ESLint v0.4.0 中引入。

资源