nodejs 文件复制 fs.createReadSream&fs.createWriteStream&pipe

文件结构:

e:nodejs/filecopy/demo.js

e:nodejs/filecopy/1/result.txt

e:nodejs/filecopy/2


demo.js:

var fs=require('fs');

var rOption={
	flags:"r",
	encoding:null,
	mode:0666
}

var wOption = {
  flags: 'a',
  encoding: null,
  mode: 0666   
}

var fileReadStream=fs.createReadStream('filecopy/1/result.txt',rOption);
var fileWriteStream = fs.createWriteStream('filecopy/2/new_result.txt',wOption);

fileReadStream.on('data',function(data){
	fileWriteStream.write(data);
});

fileReadStream.on('end',function(){
	console.log("readStream end");
	fileWriteStream.end();
});
启动运行可实现将result.txt从e:nodejs/filecopy/1/复制到e:nodejs/filecopy/2/下。


这里再补充在流中非常有用的一个函数:pipe,它以用来把当前的可读流和另外一个可写流连接起来。可读流中的数据会被自动写入到可写流中。使用起来非常方便,依然实现上例中的功能:
demo.js:

var fs = require('fs');

var fileReadStream=fs.createReadStream('filecopy/1/result.txt');
var fileWriteStream = fs.createWriteStream('filecopy/2/new_result.txt');
fileReadStream.pipe(fileWriteStream);

fileWriteStream.on('close',function(){
  console.log('copy over');  
});


你可能感兴趣的:(Node.js,杂货)