Nodejs中复制文件的四种方法

1 copyFile

fs.copyFile(src, dest[, flags], callback)

Node v8.5.0以后可用,用法如下:

fs.copyFile('./src/index.js','./dist/index.js',function(err){
	if(err) console.log('something wrong was happened')
	else console.log('copy file succeed');
}

2 readFile、writeFile

fs.readFile('./src/index.js',function(err,data){
	if(err) throw new Error('something wrong was happended');
	fs.writeFile('./dest/index.js',data,function(err){
		if(err) throw new Error('something wrong was happended');
	})
})

3 createReadStream、read、write

var file = createReadStream('./src/index.js');
var out = createWriteStream('./dist/index.js');

file.on('data',function(data){
	out.write(data)
});
file.on('end',function(){
	out.end();
})

4 pipe

let file = createReadStream('./src/index.js');
let out = createWriteStream('./dist/index.js');

file.pipe(out);

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