node.js - 创建一个包含文件夹内容的数组

标签 node.js

我有一个包含一些文本文档的文件夹,

我想创建一个包含文本文档名称的数组。

结果一定是这样的:

数组=[第一个文件.txt],[第二个文件.txt],[第三个文件.txt],ecc。

我知道我必须做这样的事情:

fs.readFile(foldername, function (err, content) {

var array = content.toString().split("...");
}

但我不知道应该在 .split() 中写什么。

有什么想法吗?谢谢。

最佳答案

您可能应该使用fs.readdir而不是fs.readFile

fs.readFile 用于获取特定文件的内容,传递给它的路径参数应该是特定文件的路径,而不是文件夹的路径。

fs.readdir 用于获取特定文件夹/目录的内容。这里的路径参数应该是文件夹的路径

Node 文档说:

Reads the contents of a directory. The callback gets two arguments (err, files) where files is an array of the names of the files in the directory excluding '.' and '..'.

Read more here 。您必须查看文件名是否包含您想要的文件扩展名。

关于node.js - 创建一个包含文件夹内容的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37854819/

相关文章:

node.js - 处理 acme-challenge Letsencrypt 请求

node.js - 在 gulp.watch 上重建项目没有效果

javascript - node.js 和 Canvas ,gameloop 不同步

javascript - 全局变量未初始化nodejs

javascript - 如何使用 N-API 将 BigInt 类型从 C++ 返回到 javascript?

javascript - Passport.js github 策略回调总是返回 "TypeError: Cannot set property ' 未定义的用户”

node.js - 我想在 Model.find() 方法的 where() 中添加一个函数,但它给出了正文中包含的拼写错误

javascript - 如何使用 setInterval(with clearInterval)使用 Bluebird Promises 发送请求?

javascript - grunt 复制将构建文件夹移动到项目之外

node.js - Socket.io 中的身份验证