Rohit Hazra
Rohit Hazra

Reputation: 667

Read a file without requiring any module (not even inbuilts)

I recently came across a question and got me thinking on how do it. The question is a Competition Question and I do not intend to participate but the question is quite intriguing.

Basically they want to read a file.txt and find a word in there from the input, but

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

this line makes me wonder, how do i read a file in JS.

Upvotes: 0

Views: 90

Answers (1)

mscdex
mscdex

Reputation: 106756

One way would be to pipe the file to node: 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();

Upvotes: 1

Related Questions