Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 217
user949300 Avatar asked Nov 11 '13 23:11

user949300


People also ask

How do I read a file in node JS?

The file needs to be in the same directory that you run the node process from. So if the file is in dir/node/index. html and so is your app. js file but you do: node /dir/node/app.

What is read stream in node JS?

Streams are objects that let you read data from a source or write data to a destination in continuous fashion. In Node.js, there are four types of streams − Readable − Stream which is used for read operation.


1 Answers

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.

like image 124
Bulkan Avatar answered Oct 11 '22 16:10

Bulkan