javascriptnode.jsfs

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

Solution

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