【问题标题】:How to read data from file System and send complete message to client?如何从文件系统读取数据并向客户端发送完整的消息?
【发布时间】:2017-03-01 21:26:01
【问题描述】:

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

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

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

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

【问题讨论】:

  • 它是可行的,但我强烈建议不要这样做,我建议您在 Solr 中索引您的文件,并在 Solr 中查询此类搜索词,或者,至少如果您没有Solr,在您拥有的任何数据库中使用它,这也是我不推荐的,但至少不是您这样做的文件搜索方式。
  • 我不能使用数据库来满足这个要求,我必须进行文件搜索。任何好的例子,我如何使用 FS 来实现。

标签: javascript node.js for-loop fs


【解决方案1】:

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

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

【讨论】:

  • 我们将来自 Kafka 总线的事件渲染为每个事件的字符串,然后将其写入文件系统。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-06-24
  • 2019-01-26
  • 1970-01-01
  • 2017-01-12
  • 2022-07-15
  • 2018-05-26
  • 1970-01-01
相关资源
最近更新 更多