首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何从文件系统中读取数据并向客户端发送完整的消息?

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

Stack Overflow用户
提问于 2017-03-02 05:26:01
回答 1查看 40关注 0票数 0

在我的实现中,如果用户从客户端进行搜索,我希望检查字符串是否是文件的一部分。我将该行数据作为响应发送回客户端。

我的问题是,假设用户想要搜索testid012。因此,在我当前的代码中,它只找到包含搜索字符串的单行。相反,我希望发送包含多行的响应,其中包含搜索字符串,在本例中为testid012。这可行吗?

searchService.js

代码语言:javascript
复制
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();
        });

编辑/server.log

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2017-03-02 06:35:24

您的解决方案是有效的,但您只得到一行的原因是您正在按行尾拆分您的输入。似乎您需要弄清楚事件是如何分开的,并更改您的data.split()调用。

如果有启动每个事件的数据,比如[EVENT] This is an event,那么使用正则表达式对其进行拆分。data.split('[EVENT] ')

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42542352

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档