简体   繁体   English

如何从文件系统读取数据并将完整的消息发送给客户端?

[英]How to read data from file System and send complete message to client?

In my implementation, if a user searches from a client, I want to check if the string is part of the file. 在我的实现中,如果用户从客户端搜索,我想检查字符串是否是文件的一部分。 I am sending that line data back to the client as a response. 我正在将该行数据发送回客户端作为响应。

My issue is lets assume that a user wants to search for testid012 . 我的问题是假设用户要搜索testid012 So with my current code, it only finds a singular line that contains the search string. 因此,使用我当前的代码,它只会找到包含搜索字符串的单行。 Instead I want to send a response with multiple lines that include the search string, which in this case is testid012 . 相反,我想发送包含搜索字符串的多行响应,在本例中为testid012 Is this doable? 这可行吗?

searchService.js searchService.js

fs.readFile('logs/dit/' + logfile.filename, 'utf8', function (err, data) {
            if (err) {
                return done(err);
            }
            var lines = data.split('\n'); // get the lines
            lines.forEach(function(line) { // for each line in lines
                if (line.indexOf(searchStr) != -1) { // if the line contain the searchSt
                    results.push({
                    filename:logfile.filename,
                    value:line
                    });
                }
            });
            // when you are done reading the file
            done();
        });

dit/server.log DIT / server.log中

testid012 Lorem test Ipsum is simply dummy text text of the printing  and typesetting industrytestid Lorem test Ipsum is simply dummy text text of the printing and typesetting industrytestid Lorem test Ipsum is simply dummy text text of the printing  and typesetting industry
Lorem test Ipsum is simply dummy text text of the printing  and typesetting industry,testid Lorem test Ipsum is simply dummy text text of the printing  and typesetting industry

testid013 Lorem test Ipsum is simply dummy text text of the printing and typesetting industry,testid Lorem test Ipsum is simply dummy text text of the printing  and typesetting industrytestid Lorem test Ipsum is simply dummy text text of the printing  and typesetting industry
Lorem test Ipsum is simply dummy text text of the printing  and typesetting industry

Your solution will work, but the reason you are only getting one line is your are splitting your input by line end. 您的解决方案可以工作,但是只得到一行的原因是您要按行尾拆分输入。 Seems like you need to figure out how your events are separated and change your data.split() call. 似乎您需要弄清楚事件是如何分隔的,并更改data.split()调用。

If there is data that starts every event like [EVENT] This is an event then use a regex to split on that. 如果有数据启动每个事件,例如[EVENT] This is an event则使用正则表达式对此进行分割。 data.split('[EVENT] ')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM