Kuru
Kuru

Reputation: 1517

I can await fs.readdir but I don't know why

https://github.com/SimulatedGREG/electron-vue

I used this template to make electron.

And I am using this library.

https://www.npmjs.com/package/fs-extra

https://nodejs.org/docs/latest-v11.x/api/fs.html

By this document, I can write like this.

await fs.readdir

But the electron template, it is using [email protected] and which is using [email protected].

So I checked here.

https://nodejs.org/docs/latest-v8.x/api/fs.html

It looks like the function doesn't return promise.

But I actually can await fs functions using fs-extra in [email protected].

Both develop and build.

Why is this?

result of

console.log(fs.readdir())

Is like below.

enter image description here

It's Promise.

But I don't know why I can do this in [email protected].

Upvotes: 3

Views: 3505

Answers (3)

jdlm
jdlm

Reputation: 6664

If you're using Node > 8.16 (I believe), you can use promisify in the utils module:

const { promisify } = require('utils');
const fs = require('fs');
const readdir = promisify(fs.readdir);

(async () => {
  const res = await readdir('./path');
  console.log(res);
})();

Upvotes: 2

Sharvin K
Sharvin K

Reputation: 715

You can use fs module in node v8. the return value will be passed to callback function

const fs = require('fs');
fs.readdir(dir, function(err, list) {

// do your logic with list array

})

Upvotes: 2

Kuru
Kuru

Reputation: 1517

Sorry, I am not good at English.

And, I am a beginner web developer.

This is just an anticipation.

I saw package.json of "fs-extra".

And I could not find "fs" inside that.

It is using a library called "graceful-fs", but this library does not require "fs" neither.

Maybe, "fs-extra" is not relevant to "fs".

And it has own logic that is already promisified even in node lower than verstion10.

Any one know the truth?

Upvotes: -3

Related Questions