在 node.js 中使用文件系统与 async/await [英] Using filesystem in node.js with async / await

查看:20
本文介绍了在 node.js 中使用文件系统与 async/await的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would like to use async/await with some filesystem operations. Normally async/await works fine because I use babel-plugin-syntax-async-functions.

但是使用这段代码,我遇到了 names 未定义的 if 情况:

But with this code I run into the if case where names is undefined:

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();

当我将代码重建到回调地狱版本中时,一切正常,我得到了文件名.谢谢你的提示.

When I rebuild the code into the callback hell version everything is OK and I get the filenames. Thanks for your hints.

推荐答案

自 Node 11 起原生支持 async await fs 函数

自 Node.JS 11.0.0(稳定版)和 10.0.0 版(实验版)以来,您可以访问已经承诺的文件系统方法,并且可以通过 try catch 异常处理,而不是检查回调的返回值是否包含错误.

Native support for async await fs functions since Node 11

Since Node.JS 11.0.0 (stable), and version 10.0.0 (experimental), you have access to file system methods that are already promisify'd and you can use them with try catch exception handling rather than checking if the callback's returned value contains an error.

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

The API is very clean and elegant! Simply use .promises member of fs object:

import fs from 'fs';
const fsPromises = fs.promises;

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

listDir();

这篇关于在 node.js 中使用文件系统与 async/await的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆