Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to copy multiple files using fs.copyFile node?

I am using fs.copyFile to copy files from one location to another. I am doing this twice in order to copy two files. It's redundant and I would like to make my code better by maybe copying both files to the destination with a single call? How can I achieve this?

fs.copyFile('src/blah.txt', 'build/blah.txt', (err) => {
        if (err) throw err;
});
fs.copyFile('src/unk.txt', 'build/unk.txt', (err) => {
        if (err) throw err;
});
like image 457
Angela Roux Avatar asked Feb 22 '19 00:02

Angela Roux


People also ask

How can we copy any folder from one location to another?

Right-click the file or folder you want, and from the menu that displays click Move or Copy. The Move or Copy window opens. Scroll down if necessary to find the destination folder you want.

Which of the following will copy a file in node JS?

With Node. js 8.5, a new File System feature is shipped by which you can copy the files using the core fs module.


1 Answers

You can simply create a function of your own that takes the src and dest path and an array of filenames as arguments:

const util = require('util');
const fs = require('fs');
const path = require('path');
const copyFilePromise = util.promisify(fs.copyFile);

function copyFiles(srcDir, destDir, files) {
    return Promise.all(files.map(f => {
       return copyFilePromise(path.join(srcDir, f), path.join(destDir, f));
    }));
}

// usage
copyFiles('src', 'build', ['unk.txt', 'blah.txt']).then(() => {
   console.log("done");
}).catch(err => {
   console.log(err);
});
like image 84
jfriend00 Avatar answered Nov 15 '22 03:11

jfriend00