斗士狗 2010-04-28 06:10 采纳率: 0%
浏览 1035
已采纳

如何在 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条回答 默认 最新

  • bug^君 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 returns the file name array, but it will stop any further execution of your code until the read process ends.

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

报告相同问题?

悬赏问题

  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制
  • ¥20 usb设备兼容性问题
  • ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
  • ¥15 安装svn网络有问题怎么办