Index

no-sync

禁止同步方法

Important

This rule was deprecated in ESLint v7.0.0. It will be removed in v11.0.0. Please use the corresponding rule in eslint-plugin-n.

Learn more

在 Node.js 中,大多数 I/O 都是通过异步方法完成的。然而,异步方法通常也有同步版本。例如,fs.exists()fs.existsSync()。在某些情况下,使用同步操作是可以的(例如,在像 ESLint 这样的命令行工具中)。然而,在其他情况下,使用同步操作被认为是不好的做法,应当避免。例如,如果你在 Node.js 上运行一个高流量的 Web 服务器,你应该仔细考虑是否允许任何可能阻塞服务器的同步操作。

🌐 In Node.js, most I/O is done through asynchronous methods. However, there are often synchronous versions of the asynchronous methods. For example, fs.exists() and fs.existsSync(). In some contexts, using synchronous operations is okay (if, as with ESLint, you are writing a command line utility). However, in other contexts the use of synchronous operations is considered a bad practice that should be avoided. For example, if you are running a high-travel web server on Node.js, you should consider carefully if you want to allow any synchronous operations that could lock up the server.

规则详情

🌐 Rule Details

此规则旨在防止在 Node.js 中调用同步方法。它特别针对方法后缀“Sync”(这是 Node.js 操作的惯例)进行查找。

🌐 This rule is aimed at preventing synchronous methods from being called in Node.js. It looks specifically for the method suffix “Sync” (as is the convention with Node.js operations).

选项

🌐 Options

此规则有一个可选的对象选项 { allowAtRootLevel: <boolean> },用于决定是否允许在文件的顶层(任何函数之外)使用同步方法。该选项默认为 false

使用默认 { allowAtRootLevel: false } 选项时,该规则的错误代码示例:

🌐 Examples of incorrect code for this rule with the default { allowAtRootLevel: false } option:

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

fs.existsSync(somePath);

function foo() {
  var contents = fs.readFileSync(somePath).toString();
}

使用默认 { allowAtRootLevel: false } 选项时,该规则的正确代码示例:

🌐 Examples of correct code for this rule with the default { allowAtRootLevel: false } option:

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

obj.sync();

async(function() {
    // ...
});

使用 { allowAtRootLevel: true } 选项违反此规则的 错误 代码示例

🌐 Examples of incorrect code for this rule with the { allowAtRootLevel: true } option

在线运行
/*eslint no-sync: ["error", { allowAtRootLevel: true }]*/

function foo() {
  var contents = fs.readFileSync(somePath).toString();
}

var bar = baz => fs.readFileSync(qux);

使用 { allowAtRootLevel: true } 选项的此规则的 正确 代码示例

🌐 Examples of correct code for this rule with the { allowAtRootLevel: true } option

在线运行
/*eslint no-sync: ["error", { allowAtRootLevel: true }]*/

fs.readFileSync(somePath).toString();

何时不使用

🌐 When Not To Use It

如果要在脚本中允许同步操作,请不要启用此规则。

🌐 If you want to allow synchronous operations in your script, do not enable this rule.

版本

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

资源