izzypt
izzypt

Reputation: 180

Is fs_promises_readdir an async function?

Basically, what I'am trying to this is to read all the files names from a directory and I found this fsPromises.readdir which does pretty much what I want :

I have taken this code from nodeJS documentation page , here :

https://nodejs.org/api/fs.html#fs_fspromises_readdir_path_options

import { readdir } from 'fs/promises'; // I changed this to : const readdir = require('fs/promises');

try {
  const files = await readdir(path);
  for await (const file of files)
    console.log(file);
} catch (err) {
  console.error(err);
}

When I run this , the console will give me the following error :


const files = await readdir(path);
                ^^^^^

SyntaxError: await is only valid in async function

This is weird since according to the documentation this function is a Promise and if it is a promise that means it is async. Right ?

So , I dont know what am I missing ?

Upvotes: 0

Views: 399

Answers (1)

IAmDranged
IAmDranged

Reputation: 3020

The error you're seeing refers to the fact that you're using the await keyword outside of an async function.

I think this is allowed in recent versions of Node, but if you're running an older version you will need to wrap your code in an async function.

(async function() {
    try {
      const files = await readdir(path);
      for await (const file of files)
        console.log(file);
    } catch (err) {
      console.error(err);
    })()
}()

Upvotes: 1

Related Questions