如何获取 Node.js 目录中所有文件的名称列表? [英] How do you get a list of the names of all files present in a directory in Node.js?

查看:44
本文介绍了如何获取 Node.js 目录中所有文件的名称列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 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?

推荐答案

您可以使用 fs.readdirfs.readdirSync 方法.fs 包含在 Node.js 核心中,因此无需安装任何东西.

You can use the fs.readdir or fs.readdirSync methods. fs is included in Node.js core, so there's no need to install anything.

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.

这篇关于如何获取 Node.js 目录中所有文件的名称列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆