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
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With