无需任何模块即可读取文件(甚至不需要内置)

时间:2016-04-28 03:33:48

标签: node.js

我最近遇到了一个问题并让我思考如何做到这一点。问题是竞赛问题,我不打算参加,但这个问题非常有趣。

基本上他们想要读取file.txt并从输入中找到一个单词,但是

It is not allowed to require any JS modules, not even the standard ones built into Node.js

这一行让我想知道,我如何在JS中读取文件。

1 个答案:

答案 0 :(得分:1)

一种方法是将文件传递给节点:cat foo.txt | node foo.js

<强> foo.js:

var buf = '';
process.stdin.on('data', function(chunk) {
  buf += chunk;
}).on('end', function() {
  if (buf.indexOf('word') !== -1)
    console.log('Found word!');
  else
    console.log('Did not find word!');
}).resume();