user949300
user949300

Reputation: 15729

How do you read a file or Stream synchronously in node.js?

Please, no lectures about how I should be doing everything asynchronously. Sometimes I want to do things the easy obvious way, so I can move on to other work.

For some reason, the following code doesn't work. It matches code I found on a recent SO question. Did node change or break something?

var fs = require('fs');
var rs = fs.createReadStream('myfilename');  // for example
                                             // but I might also want to read from
                                             // stdio, an HTTP request, etc...
var buffer = rs.read();     // simple for SCCCE example, normally you'd repeat in a loop...
console.log(buffer.toString());

After the read, the buffer is null.

Looking at rs in the debugger, I see

events  
   has end and open functions, nothing else
_readableState
  buffer = Array[0]
  emittedReadable = false
  flowing = false   <<< this appears to be correct
  lots of other false/nulls/undefined
fd = null   <<< suspicious???
readable = true
  lots of other false/nulls/undefined

Upvotes: 38

Views: 33985

Answers (1)

Bulkan
Bulkan

Reputation: 2592

To read the contents of a file synchronously use fs.readFileSync

var fs = require('fs');
var content = fs.readFileSync('myfilename');
console.log(content);

fs.createReadStream creates a ReadStream.

Upvotes: 9

Related Questions