no-sync

禁止同步方法

该规则在 ESLint v7.0.0 中已弃用。请使用 eslint-plugin-n 中的相应规则。

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

在 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

¥This rule has an optional object option { allowAtRootLevel: <boolean> }, which determines whether synchronous methods should be allowed at the top level of a file, outside of any functions. This option defaults to 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 中引入。

资源

ESLint 中文网
粤ICP备13048890号