javascript - 使用 Node.js 的 fs.readFile() 返回出现字符串的行

标签 javascript node.js fs

我正在搜索一个大型的 n-gram 外部文件(大约 100 万行)以查找特定字符串的实例,并希望能够从该字符串出现的文件中返回整行。想知道这是否可能以及如何可能。 这是我目前的代码:

 composeLines = function(importantWords, cb) {
    var word = importantWords.shift();

    fs.readFile("./w5_.txt", function(err, cont) {
      if (err) throw err;
      console.log("String"+(cont.indexOf(word)>-1 ? " " : " not ")+"found");

      cb(importantWords);
    });

  };

使用这段代码,我能够确定文件 w5_.txt 是否包含一些很棒的字符串,但我需要能够获得它所属的 n-gram。例如。搜索“设计”将从文件中返回 n-gram“设计的一部分”。

如有任何帮助,我们将不胜感激。

最佳答案

一种选择是使用正则表达式:

// Make sure `word` is properly escaped first

// 'm' allows '^' and '$' to match line boundaries or
// start and beginning of the input (respectively)
var re = new RegExp('^.*' + word + '.*$', 'm');
var m = re.exec(cont);
if (m)
  console.log('Word %j found on line: %j', word, m[0]);
else
  console.log('Word %j not found', word);

关于javascript - 使用 Node.js 的 fs.readFile() 返回出现字符串的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36414187/

相关文章:

javascript - 如何使用node.js的fs api提取doc/docx的内容

javascript - 如何阻止 PHP 页面中的 javascript 片段加载到屏幕分辨率较小的设备上

javascript - javascript中匿名函数的索引和值输入的解释

javascript - 如何使用 ng-repeat :Angularjs?

mysql - 链接应用程序与数据库

javascript - 如何使用node.js打开服务器上的文件

javascript - ember-i18n - 内部化支持

node.js - 从 github 在 azure 上部署默认 Angular 应用程序会出现错误

node.js - 无法删除文件,我没有得到详细的 ENOENT

javascript - Node (express.js) next() 在流结束之前调用