Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/facebook/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何从文件系统读取数据并向客户端发送完整的消息?_Javascript_Node.js_For Loop_Fs - Fatal编程技术网

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

Javascript 如何从文件系统读取数据并向客户端发送完整的消息?,javascript,node.js,for-loop,fs,Javascript,Node.js,For Loop,Fs,在我的实现中,如果用户从客户端搜索,我想检查字符串是否是文件的一部分。我将该行数据作为响应发送回客户机 我的问题是假设用户想要搜索testd012。因此,在我当前的代码中,它只找到一个包含搜索字符串的单数行。相反,我希望发送一个包含搜索字符串的多行响应,在本例中是testid012。这可行吗 searchService.js fs.readFile('logs/dit/' + logfile.filename, 'utf8', function (err, data) {

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

我的问题是假设用户想要搜索
testd012
。因此,在我当前的代码中,它只找到一个包含搜索字符串的单数行。相反,我希望发送一个包含搜索字符串的多行响应,在本例中是
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

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

如果有数据启动每个事件,如
[event],这是一个事件
,则使用正则表达式对其进行拆分。
data.split(“[EVENT]”)是可以做到的,但我强烈建议不要这样做,我建议您在Solr中索引您的文件,并在Solr中查询此类搜索词,或者,至少如果您没有Solr,在你拥有的任何数据库中使用它,这也是我不推荐的,但至少不是像你这样做的文件搜索。我不能使用数据库来满足这个要求,我必须使用文件搜索。任何一个好的例子,我如何使用FS.we实现这一点,我们将来自Kafka总线的事件呈现为字符串,每个事件都将其写入文件系统。