node.js - 有没有办法在 node.js 中加载和写入整个文件夹?
问题描述
我需要能够将整个文件夹以及其中可能包含的任何文件加载到 json 或字符串格式的变量中。我还需要能够获取这个 json 或字符串,并使用它来创建一个与我加载的内容相同的新文件夹。有没有一种简单的方法可以做到这一点,或者你们建议的 npm 模块?
我搜索了一个可以执行此操作的 npm 模块,但我发现的所有模块要么使用单个文件,要么不允许反转过程并创建文件夹。
解决方案
您可以使用节点文件系统命令。例如,您可以使用fs.readdir获取文件夹中的所有文件名:
//First you have to require fs
const fs = require('fs');
//You can read a directory like this
fs.readdir(`./your/dir/absolute/path`, (err, files) => {
//This function will return all file names if existed
});
您可以使用fs.readFile读取文件:
//First you have to require fs
const fs = require('fs');
//You can read a directory like this
fs.readdir(`./your/dir/absolute/path`, (err, files) => {
//If there is file names use fs.readFile for each file name
if(!err, files){
files.forEach(fileName => {
fs.readFile('./your/dir/absolute/path/' + fileNmae, 'utf8', (err,data){
//You will get file data
})
})
}
});
您可以使用fs.open和fs.writeFile在另一个文件夹中创建具有相同数据的文件:
const fs = require('fs');
//You can read a directory like this
fs.readdir(`./your/dir/absolute/path`, (err, files) => {
//If there is file names use fs.readFile for each file name
if(!err, files){
files.forEach(fileName => {
fs.readFile('./your/dir/absolute/path/' + fileNmae, 'utf8', (err,data){
//Use fs.open to copy data to a new file in a new dir
fs.open('./new/folder/absolute/path' + newFileName, 'wx', (err, fd) => {
//If file created you will get a file file descriptor
if(!err && fd){
//Turn data to sting if needed
var strData = JSON.stringify(data)
//Use fs.writeFile
fs.writeFile(fd, strData, (err) => {
//Close the file
fs.close(fd, (err) => {
//if no err callback false
})
})
}
})
})
})
}
});
推荐阅读
- json - Google 表格在 Postman 中以 CSV 格式输出。如何输出为 JSON?
- flutter - Flutter 周期性刷新和弹出所有其他页面导致错误
- reactjs - 主页中的 React Router 目标 div id
- javascript - 如何只调用一次函数
- ansible - 如果跳过相关步骤,则跳过 ansible 进度任务
- python - 尝试在 Pandas 中编辑巨大数据框的特定部分
- api - YouTube Data API playlistItems:列表仅返回最多 100 个数据项 - 或 2 页数据,在 7 月 16 日正常工作
- sapui5 - UI5 模块命名空间
- multithreading - 确定为什么在 Delphi 中关闭任务对话框
- javascript - TypeError:无法读取未定义的属性“地图”| 不和谐.js