node.js 复制文件最快的方法

偶尔需要复制个文件,不用太复杂的库,简单写个函数即可。

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

Fastest way to copy file in node.js

作者: meathill

爱编程,爱旅游,爱吐槽。 今年的目标是完成并运营至少一个 Side Project。 《Electron + Vue 实战开发》龟速创作中……

欢迎吐槽,请勿装死

This site uses Akismet to reduce spam. Learn how your comment data is processed.