~Onlooker 2010-04-28 06:10 采纳率: 0%
浏览 995
已采纳

如何在 Node.js 中获取目录中所有文件的名称列表?

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?

转载于:https://stackoverflow.com/questions/2727167/how-do-you-get-a-list-of-the-names-of-all-files-present-in-a-directory-in-node-j

  • 写回答

16条回答 默认 最新

  • 10.24 2010-04-28 06:15
    关注

    You can use the fs.readdir or fs.readdirSync methods.

    fs.readdir

    const testFolder = './tests/';
    const fs = require('fs');
    
    fs.readdir(testFolder, (err, files) => {
      files.forEach(file => {
        console.log(file);
      });
    })
    

    fs.readdirSync

    const testFolder = './tests/';
    const fs = require('fs');
    
    fs.readdirSync(testFolder).forEach(file => {
      console.log(file);
    })
    

    The difference between the two methods, is that the first one is asynchronous, so you have to provide a callback function that will be executed when the read process ends.

    The second is synchronous, it will return the file name array, but it will stop any further execution of your code until the read process ends.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(15条)

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置