How to copy multiple files from one folder to another using Fs.copy

Asked

Viewed 479 times

0

I wonder how I do to copy more than one file to another location (folder). Using the fs.Copyfilesync. In the example I can only copy one file:

Example:

fs.copyFileSync('C:/xmlpath/file.xml', 'C:/test/file.xml');

1 answer

1


You can use the following code:

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

// Uso
copyFiles('src', 'build', ['unk.txt', 'blah.txt']).then(() => {
   console.log("done");
}).catch(err => {
   console.log(err);
});

With const copyFilePromise = util.promisify(fs.copyFile); the function is transformed into a Promise to facilitate the use, in the function copyFiles is received the source folder (srcDir), the destination folder (destDir) and the file listing (files), then returns a Promise with the Promise. giving a map in files

This way it will do the copying process in parallel, not being necessary to wait for each copy to finish to run the next

I removed the code of that reply

Browser other questions tagged

You are not signed in. Login or sign up in order to post.