How do you get a list of the names of all files present in a directory in Node.js?

后端 未结 25 1287
天涯浪人
天涯浪人 2020-11-22 07:47

I\'m trying to get a list of the names of all the files present in a directory using Node.js. I want output that is an array of filenames. How can I do this?

25条回答
  •  忘了有多久
    2020-11-22 08:12

    Using Promises with ES7

    Asynchronous use with mz/fs

    The mz module provides promisified versions of the core node library. Using them is simple. First install the library...

    npm install mz
    

    Then...

    const fs = require('mz/fs');
    fs.readdir('./myDir').then(listing => console.log(listing))
      .catch(err => console.error(err));
    

    Alternatively you can write them in asynchronous functions in ES7:

    async function myReaddir () {
      try {
        const file = await fs.readdir('./myDir/');
      }
      catch (err) { console.error( err ) }
    };
    

    Update for recursive listing

    Some of the users have specified a desire to see a recursive listing (though not in the question)... Use fs-promise. It's a thin wrapper around mz.

    npm install fs-promise;
    

    then...

    const fs = require('fs-promise');
    fs.walk('./myDir').then(
        listing => listing.forEach(file => console.log(file.path))
    ).catch(err => console.error(err));
    

提交回复
热议问题