Skip to content

Instantly share code, notes, and snippets.

@repejota
Created August 18, 2012 21:08
Show Gist options
  • Save repejota/3389886 to your computer and use it in GitHub Desktop.
Save repejota/3389886 to your computer and use it in GitHub Desktop.
Node js module that copy a file asyncrhonously using streams and calls a _callback_ when it finishes.
var fs = require("fs"),
util = require('util');
// Copy a file asyncrhonously using streams and calls a _callback_ when it
// finishes.
exports.cp = (function() {
return function (src, dst, cback, o) {
// Options can have:
//
// * **force**: (*bool*) wich determines if files are being overriten.
o = o || {};
// Check if destination file exists
fs.stat(dst, function (err) {
// If file exists shows error unless _force_ is true.
if ((!err) && !o.force) return cback(new Error(dst+" exists."));
// If not exists or _force_ is true copy files using streams.
fs.stat(src, function (err) {
if (err) return cback(err);
util.pump(fs.createReadStream(src),
fs.createWriteStream(dst),
cback);
});
});
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment