//since the process.stdin is a stream
//and a stream implements
//event emitter class,
//we are able to listen
//to its event when data
//is coming in stdin
process.stdin.on('data', handler)
const handler = (data) => {
console.log(data)
}
<Buffer 64 73 66 73 64 66 0a>
//set encoding
process.stdin.setEncoding('utf8')
//print data on standard input
process.stdin.on('data', console.log)
// lets read a file
const fs = require("fs")
const rs = fs.createReadStream("./003.js", "utf8");
rs.on("data", (chunk) => {
console.log(chunk);
});
rs.on("end", () => {
console.log("done reading from stream..");
});
The 'end' event is emitted when there is no more data to be consumed from the stream.
The 'close' event is emitted when the stream and any of its underlying resources (a file descriptor, for example) have been closed. The event indicates that no more events will be emitted, and no further computation will occur.
const { Writable } = require('stream');
const ws = new Writable({
write(chunk) {
process.stdout.write(chunk)
}
})
process.stdin.pipe(ws)
uncork()
cork()
const fs = require("fs");
const { Writable } = require('stream');
const ws = new Writable({
write(c) {
process.stdout.write(c)
}
})
ws.cork()
ws.write('hello!')
ws.write('hello agian!')
setImmediate(() => {
console.log('uncorking...')
ws.uncork();
})
const { Writable } = require('stream');
const ws = new Writable({
write(chunk, _, cb) {
process.stdout.write(chunk)
setTimeout(() => {
cb();
}, 10)
}
})
let isDrained = true;
ws.on('drain', () => {
console.log('Drain event!')
})
setInterval(() => {
// console.log('is writable?', ws.writable)
if(isDrained) {
isDrained = ws.write("Hello!", () => {
// console.log("written!")
})
console.log(isDrained)
}
}, 1)