我想在一些文件系统操作中使用async/await。通常async/await工作正常,因为我使用babel-plugin-syntax-async-functions。

但在这段代码中,我遇到了name未定义的if情况:

import fs from 'fs';

async function myF() {
  let names;
  try {
    names = await fs.readdir('path/to/dir');
  } catch (e) {
    console.log('e', e);
  }
  if (names === undefined) {
    console.log('undefined');
  } else {
    console.log('First Name', names[0]);
  }
}

myF();

当我将代码重建为回调地狱版本时,一切都OK,我得到了文件名。 谢谢你的提示。


当前回答

节点v14.0.0及以上版本

你可以这样做:

import { readdir } from "fs/promises";

就像从fs导入一样

更多细节请参见此PR: https://github.com/nodejs/node/pull/31553

其他回答

节点v14.0.0及以上版本

你可以这样做:

import { readdir } from "fs/promises";

就像从fs导入一样

更多细节请参见此PR: https://github.com/nodejs/node/pull/31553

从v10.0开始,您可以使用fs。承诺

使用readdir的示例

const { promises: fs } = require("fs");

async function myF() {
    let names;
    try {
        names = await fs.readdir("path/to/dir");
    } catch (e) {
        console.log("e", e);
    }
    if (names === undefined) {
        console.log("undefined");
    } else {
        console.log("First Name", names[0]);
    }
}

myF();

使用readFile的示例

const { promises: fs } = require("fs");

async function getContent(filePath, encoding = "utf-8") {
    if (!filePath) {
        throw new Error("filePath required");
    }

    return fs.readFile(filePath, { encoding });
}

(async () => {
    const content = await getContent("./package.json");

    console.log(content);
})();

您可以使用简单而轻量级的模块https://github.com/nacholibre/nwc-l,它同时支持异步和同步方法。

注:这个模块是我自己创建的。

您可能会产生错误的行为,因为File-Api文件。Readdir不返回承诺。它只需要一个回调。如果你想使用async-await语法,你可以像这样“许诺”函数:

function readdirAsync(path) {
  return new Promise(function (resolve, reject) {
    fs.readdir(path, function (error, result) {
      if (error) {
        reject(error);
      } else {
        resolve(result);
      }
    });
  });
}

叫它:

names = await readdirAsync('path/to/dir');

从Node 11开始原生支持async/await fs函数

自从Node.JS 11.0.0(稳定)和10.0.0版本(实验)以来,你可以访问已经承诺的文件系统方法,你可以使用它们来处理try catch异常,而不是检查回调的返回值是否包含错误。

API非常干净和优雅!只需使用fs对象的.promises成员:

import fs from 'fs';

async function listDir() {
  try {
    return await fs.promises.readdir('path/to/dir');
  } catch (err) {
    console.error('Error occurred while reading directory!', err);
  }
}

listDir();