public
Created

How to copy file using pipe

  • Download Gist
funny-pipes.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
var copy = function(from, to, cb){
var fromStream = fs.createReadStream(from)
fromStream.on('error', cb)
var toStream = fs.createWriteStream(to)
toStream.on('error', cb)
fromStream.on('end', cb)
fromStream.pipe(toStream)
}
 
copy('non existing file a', 'non existing dir/file b', function(err){
console.log(err)
})
 
// Error will be reported twice:
//
// { [Error: ENOENT, open 'non existing file a'] errno: 34,
// code: 'ENOENT', path: 'non existing file a' }
// { [Error: ENOENT, open 'non existing dir/file b'] errno: 34,
// code: 'ENOENT', path: 'non existing dir/file b' }

With callbacks it may be something like that

var copy = function(from, to, cb){    
  var fromStream = fs.createReadStream(from, function(err){
    if(err) return cb(err)    
    var toStream = fs.createWriteStream(to, function(err){
      if(err) return cb(err)

      fromStream.on('error', cb)
      toStream.on('error', cb)
      fromStream.on('end', cb)
      fromStream.pipe(toStream)
    })    
  })  
}

With callbacks it may be something like that

var copy = function(from, to, cb){    
  var fromStream = fs.createReadStream(from, function(err){
    if(err) return cb(err)    
    var toStream = fs.createWriteStream(to, function(err){
      if(err) return cb(err)

      fromStream.on('error', cb)
      toStream.on('error', cb)
      fromStream.on('end', cb)
      fromStream.pipe(toStream)
    })    
  })  
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.