1.输入输出流三种方式:
(1) 读取图片
varfs=require('fs');
varcontentText=fs.readFileSync('444.jpg','base64'); //文本用utf8
vardataBuffer= newBuffer(contentText,'base64');//把base64码转成buffer对象,
fs.writeFile('999.jpg',dataBuffer,function(err) {
if(err){
console.log('eerr');
return;
}
console.log("ok");
})
(2)没有回调函数的
functioncreateFileName(){
vardate=newDate().valueOf();//将时间转换成毫秒
varrandom=Math.random();
returndate+''+random;
}
varfs=require('fs');
varreadStream=fs.createReadStream('kk.txt');
// readStream.setEncoding('utf8');
varwriteStream=fs.createWriteStream(createFileName()+'.txt');
readStream.pipe(writeStream);
(3)用监听读取文件流
var fs=require('fs');
var readStream=fs.createReadStream('8.png');
// readStream.setEncoding('utf8');
varwriteStream=fs.createWriteStream(createFileName()+'.png');
varcontent='';
readStream.on('data',function(chunk){
content=chunk;
});
readStream.on('end',function(){
console.log(content.toString());
writeStream.write(content,'utf8');
writeStream.end();});
readStream.on('error',function(err){
console.log(err.message);
});