Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 views
in Technique[技术] by (71.8m points)

javascript - 如何获取Node.js目录中存在的所有文件的名称列表?(How do you get a list of the names of all files present in a directory in Node.js?)

I'm trying to get a list of the names of all the files present in a directory using Node.js.

(我正在尝试使用Node.js获取目录中存在的所有文件的名称列表。)

I want output that is an array of filenames.

(我想要输出是一个文件名数组。)

How can I do this?

(我怎样才能做到这一点?)

  ask by resopollution translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

(您可以使用fs.readdirfs.readdirSync方法。)

fs.readdir

(fs.readdir)

const testFolder = './tests/';
const fs = require('fs');

fs.readdir(testFolder, (err, files) => {
  files.forEach(file => {
    console.log(file);
  });
});

fs.readdirSync

(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.

(第二个是同步的,它将返回文件名数组,但它将停止进一步执行代码,直到读取过程结束。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...