Using filesystem in node.js with async / await

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.

11 Answers
11

Leave a Comment