41. What are streams in Node.js? Explain the different types of streams present in Node.js.
A stream is an abstract interface for working with streaming data in Node.js.A request to an HTTP server and process.stdout are both stream instances.
Streams can be readable, writable, or both.
Streams are instances of EventEmitter.
Different types of streams:
Readable - Used to read the data from source.
Writable - Used to write the data to destination.
Duplex - Used to read and write the data from source to destination.
Transform - Duplex with capability to modify/transform the data.
42. What is Piping the Streams ?
Pipe in stream is used to read data from a source and pipe (write) it to a destination untill the source emits end().
const fs = require('fs');
const server = require('http').createServer();
server.on('request', (req, res) => {
const src = fs.createReadStream('./big.file');
src.pipe(res);
});
server.listen(8000);
Note:
By default end() is called on the destination when the source stream emits end, so that destination is no longer writable.
If end wasn't called on the response object, the request would time out.
43. What are Buffers?
A buffer is an area of memory.
It represents a fixed-size chunk of memory (can't be resized) allocated outside of the V8 JavaScript engine.
It is like an array of integers, which each represents a byte of data.
It is implemented by the help of Node Buffer class.
44. Difference between Streams and Buffer?
Difference between a buffer and a stream is that a stream is a sequence that transfers information from or to a specified source, whereas a buffer is a sequence of bytes that is stored in memory.
45. How to create a buffer and different types to create?
Buffer.alloc()
Buffer.allocUnsafe()
Buffer.from()
require('buffer').Buffer
const buf1 = Buffer.alloc(10, 1);
const buf2 = Buffer.allocUnsafe(5);
const buf3 = Buffer.from([1, 2, 3]);
46. What is the difference between Buffer.alloc(), and Buffer.allocUnsafe()?
Buffer.alloc(size) -
It creates a zero-filled Buffer of size length
Buffer.allocUnsafe(size) -
It creates an uninitialized buffer of size length
This is faster than calling Buffer.alloc().
The returned Buffer instance might contain old data that needs to be overwritten using either fill() or write()
47. What is the difference between Buffer.alloc(), and Buffer.from() ?
Buffer.alloc(size) -
It creates a zero-filled Buffer of size length
Buffer.from(buffer/arrayBuffer) -
It returns a new Buffer that shares the same allocated memory as the given ArrayBuffer/Buffer
48. What is the default encoding of Buffer in Node.js ?
'utf8' is the default encoding.
49. How to check if the given object is a buffer ?
Buffer.isBuffer(obj)
Tests if obj is a Buffer.
50. Can we convert Buffer to JSON ? If yes How?
Yes by using the buffer.toJSON()
var buf = new Buffer('DritalConnect');
var json = buf.toJSON(buf);
console.log(json);