美文网首页
Node.js readline (日志文件逐行读取)

Node.js readline (日志文件逐行读取)

作者: 龚达耶 | 来源:发表于2019-05-16 14:14 被阅读0次

    在我们使用Node.js的过程中可能会遇到需要一行一行读取数据列入log日志文件或者某些txt文件,那在这里我们就可以使用Node.js提供的readline。

    原文链接

    如果我们要逐行读取首先会用到createInterface,参数为一个对象。对象中我们一般会包含input和output或者一些函数。接下来这个列子我们只使用input并且将读取的内容逐行打印,使用line事件。当打印完后调用close事件。

    const readline = require('readline');
    const fs = require('fs');
    
    
    const rl = readline.createInterface({
        input: fs.createReadStream('../logs/newApp.log')
    });
    rl.on('line', (line) => {
        console.log(line)
    });
            
    rl.on('close', ()=> {
        console.log('closed')
    });
    

    运行结果

    [2019-05-13T21:06:11.155] [INFO] newApp - start to get data from CBT tool
    [2019-05-13T21:06:11.183] [INFO] newApp - last date is -------------2019-05-12
    [2019-05-13T21:06:11.183] [INFO] newApp - start running job
    closed
    

    但是如果说我们需要将逐行获取到的数据全部统计起来并返回的话。我们需要用到fs.stat来获取文件。并将读取到的内容装进数组。因为是异步的所以我们使用async,接下来将数组返回给前台。

    const readline = require('readline');
    const fs = require('fs');
    
    const viewChangeName =  async (req, res) => {
        try {
            const arr = await readLog('logs/updateAppName.log')
            res.send(arr)
        } catch (e) {
            res.send(e)
        }
    }
    
    
    const readLog = filepath => {
        return new Promise((resolve, reject) => {
            const arr = [];
            var stats = fs.stat(filepath, function(err,stats){
                if (stats && stats.isFile() ) {
                    const rl = readline.createInterface({
                        input: fs.createReadStream(filepath)
                    });
                    rl.on('line', (line) => {
                        arr.unshift(line)
                    });
                
                    rl.on('close', ()=> {
                        resolve(arr)
                    });
                } else {
                    resolve(['The record is empty'])
                }
            });
        })
        
    }
    

    相关文章

      网友评论

          本文标题:Node.js readline (日志文件逐行读取)

          本文链接:https://www.haomeiwen.com/subject/cukiaqtx.html