首页 > 解决方案 > 有没有办法在 node.js 中加载和写入整个文件夹?

问题描述

我需要能够将整个文件夹以及其中可能包含的任何文件加载到 json 或字符串格式的变量中。我还需要能够获取这个 json 或字符串,并使用它来创建一个与我加载的内容相同的新文件夹。有没有一种简单的方法可以做到这一点,或者你们建议的 npm 模块?

我搜索了一个可以执行此操作的 npm 模块,但我发现的所有模块要么使用单个文件,要么不允许反转过程并创建文件夹。

标签: node.js

解决方案


您可以使用节点文件系统命令。例如,您可以使用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.openfs.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
                            })
                        })
                    }
                })
            }) 
        })
    }
});

推荐阅读