发布于 4年前

Node.js createReadStream的使用

var fs = require('fs');
/*
*获取本地json文件数据
*参数:(dirname) dirname文件的绝对路径
*返回一个promise对象  成功:返回JSON字符串
*/
getJson=function(dirname){
    var readStream =fs.createReadStream(dirname);
    readStream.setEncoding('UTF-8');
    var data='';
    var promise=new Promise(function(resolve,reject){
            readStream.on('data',function(chunk){
                data+=chunk;
        })
        readStream.on('end',function(){
                data=data.replace(/(http:\/\/)/mg,"http:##");
                data=data.replace(/(\/\/.*$)|(\/\*.*\*\/)/mg,"");
            data=data.replace(/(http:##)/mg,"http://");
            resolve(data);
        })
        readStream.on('error',function(err){
            console.log(err);
            reject(err);
        })
    })
    return promise;
};
©2020 edoou.com   京ICP备16001874号-3