Last Updated: July 12, 2018
·
115
· ms_bit

Copy files with Node

This module exports a function that copy files from the system.
It returns a promise.

const fs = require('fs');

module.exports = function (source, target) {
    const rd = fs.createReadStream(source);
    const wr = fs.createWriteStream(target);

    return new Promise((resolve, reject) => {
        rd.on('error', reject);
        wr.on('error', reject);
        wr.on('finish', resolve);
        rd.pipe(wr);
    }).catch(error => {
        rd.destroy();
        wr.end();
        throw error;
    });
}