1、node.js中文件读取流方式:
var fs=require("fs");
var data;
var s1=fs.createReadStream("input.txt");
s1.on("data",function(txt){
data+=txt;
})
s1.on("end",function(){
console.log("文件流式读取成功!")
})
2、管道方式:
var fs=require("fs");
var s1=fs.createReadStream("input.txt");
var s2=fs.createWriteStream("output.txt");
s1.pipe(s2)
3、获取请求的网站信息:
var https=require("https");
var fs=require("fs");
https.get("https://www.baidu.com/",function(res){
var data;
res.on("data",function(txt){
data+=txt;
})
res.on("end",function(){
//console.log(data)
fs.writeFile("input.txt",data,function(){
console.log("文件写入完成!")
})
})
4、批量下载图片:
var http=require("http");
var fs=require("fs");
//利用path模块,对url进行解析,以便得到想要的相关root、base等信息;
var path=require("path");
http.get("http://www.itsource.cn/",function(res){
var data;
res.on("data",function(txt){
data+=txt;
})
res.on("end",function(){
var reg=/src="((.*?).jpg)"/img;
var filename;
while(filename=reg.exec(data)){
getImg(filename[1]);
};
// fs.writeFile("input.txt",filename[1],function(){
// console.log("文件写入成功!")
})
})
function getImg(url){
var obj=path.parse(url);
var fn=obj.base;
var stream1=fs.createWriteStream("./files/"+fn);
if(obj.root.length===0){
url="/"+url;
}
url="http://www.itsource.cn"+url;
http.get(url,function(res){
res.pipe(stream1);
console.log(fn+"读取完毕!")
})
}