0

I need to be able to load a entire folder as well as any files it may have in it into a variable in json or string format. I also need to be able to take this json or string and use it to make a new folder with the same contents as the one I loaded. Is there a easy way to do this or a npm module that any of you would suggest?

I searched for a npm module that could do this, but all the ones that I found either work with single files or don't allow for reversing the process and making a folder.

Daniel N
  • 1
  • 3
  • Possible duplicate of [Get all directories within directory nodejs](https://stackoverflow.com/questions/18112204/get-all-directories-within-directory-nodejs) – Kunal Mukherjee May 10 '19 at 15:50

2 Answers2

1

You can use node file system commands. For example, you can use fs.readdir to get all file names in a folder:

//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
});

You can use fs.readFile to read a file:

//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
            }) 
        })
    }
});

You can create a file with the same data in a another folder using fs.open and 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
                            })
                        })
                    }
                })
            }) 
        })
    }
});
majid jiji
  • 404
  • 3
  • 7
0

Have you look at something like Gulp? https://gulpjs.com/docs/en/api/src You can also pipe in your custom function and do whatever you need to do with each file.

noobius
  • 1,529
  • 7
  • 14