Subway
最快的方法
var fs = require('fs');
fs.createReadStream('test.log').pipe(fs.createWriteStream('newLog.log'));
改进使其可以接受回调
function copy(source, to, callback) {
var read = fs.createReadStream(source);
source.on('error', function (err) {
done(err);
}
var write = fs.createWriteStream(to);
write.on('error', function (err) {
done(err);
}
write.on('finish', function () {
done();
}
read.pipe(write);
function done(err) {
if (err) {
throw err;
}
callback();
}
}
继续添加 Promise,并且用 ES2015 的写法
function copy(source, to) {
return new Promise( resolve => {
let read = fs.createReadStream(source);
source.on('error', err => {
throw err;
});
let write = fs.createWriteStream(to);
write.on('error', err => {
throw err;
});
write.on('finish', ()=> {
resolve();
});
read.pipe(write);
});
}
// example
copy('a.txt', 'b.txt')
.then( () => {
console.log('copy success');
})
.catch( err => {
console.log('copy error: ', err);
});
来源:StackOverflow
欢迎吐槽,共同进步