【问题标题】:Is there a way to load and write entire folders in node.js?有没有办法在 node.js 中加载和写入整个文件夹?
【发布时间】:2019-09-28 13:26:06
【问题描述】:

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

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

【问题讨论】:

标签: node.js


【解决方案1】:

您可以使用节点file system 命令。例如,您可以使用 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
                            })
                        })
                    }
                })
            }) 
        })
    }
});

【讨论】:

    【解决方案2】:

    你看过像 Gulp 这样的东西吗? https://gulpjs.com/docs/en/api/src 您还可以通过管道输入您的自定义函数并对每个文件执行您需要执行的任何操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-01-05
      • 2021-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-07
      相关资源
      最近更新 更多