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

时间:2017-03-01 21:26:01

标签: javascript node.js for-loop fs

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

我的问题是假设用户想要搜索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

1 个答案:

答案 0 :(得分:0)

您的解决方案可行,但您只获得一行的原因是您按行结束分割输入。您似乎需要了解事件的分离方式并更改$.each(data.categories, function(category, items) { // `category` is either "cat1" or "cat2" // `items` is an array var $element = $('#' + category); $.each(items, function(index, value) { var itemHtml = '<div>Layout</div>' // sample only $element.append(itemHtml); }); }); 来电。

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