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

查看:241
本文介绍了在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.

但是这个代码我遇到的情况是名称未定义:

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.

推荐答案

从节点8.0.0开始,您可以使用:

Starting with node 8.0.0, you can use this:

import fs from 'fs';
import {promisify} from 'util';

const readdir = promisify(fs.readdir);

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

myF();

参见 https://nodejs.org/dist/latest-v8.x/docs/api/util.html#util_util_promisify_original

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

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