Skip to content

Instantly share code, notes, and snippets.

@al6x
Created October 8, 2012 00:31
Show Gist options
  • Save al6x/3850106 to your computer and use it in GitHub Desktop.
Save al6x/3850106 to your computer and use it in GitHub Desktop.
How to copy file using pipe
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' }
@al6x
Copy link
Author

al6x commented Oct 8, 2012

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)
    })    
  })  
}

@al6x
Copy link
Author

al6x commented Oct 8, 2012

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)
    })    
  })  
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment