Please enable JavaScript.
Coggle requires JavaScript to display documents.
NodeJS Modules (Buffer (Creating a Buffer (// Creates an uninitialized…
NodeJS Modules
Buffer
Description
Instances of the Buffer class are similar to arrays of integers but correspond to fixed-sized, raw memory allocations outside the V8 heap. Buffers can not be resized.
-
Creating a Buffer
// Creates an uninitialized buffer of length 10.
// Faster than Buffer.alloc() but might contain old data that needs to be overwritten using either fill() or write().
const buf3 = Buffer.allocUnsafe(10);
-
// Creates a Buffer of length 10, filled with 0x1.
const buf2 = Buffer.alloc(10, 1);
// Creates a Buffer containing Latin-1 bytes [0x74, 0xe9, 0x73, 0x74].
const buf6 = Buffer.from('tést', 'latin1');
-
-
Buffers and Encodings
Buffers are commonly used to represent sequences of encoded characters such as UTF-8, UCS2, etc. Converting between Buffer instances and JS strings can be done the following way:
const buf = Buffer.from('hello world', 'ascii');
// Prints: 68656c6c6f20776f726c64
console.log(buf.toString('hex'));
// Prints: hello world
console.log(buf.toString('ascii'));
-
Common Methods
- buf.write(string[, offset[, length]][, encoding]) - Writes string to buf at offset according to the character encoding in encoding. The length parameter is the number of bytes to write.
- buf.values() - Creates and returns an iterator for buf values. Called automatically when a Buffer is used in a for..of statement.
- buf.slice([start[, end]]) - Returns a new Buffer that references the original memory, but offset and cropped by the start and end indices.
-
Cluster
Description
The module allows for easy creation of child processes that all share server ports. Such cluster of Node.js processes allows the programmer to take advantage of multi-core systems.
-
Creating a Cluster
const cluster = require('cluster');
...
const numCPUs = require('os').cpus().length;
...
if(cluster.isMaster){
for (let i = 0; i < numCPUs; i++){
cluster.fork();
}
}
-
How it works
The worker processes are spawned using the child_process.fork() method, which enables communication via IPC.
Workers can be killed or re-spawned depending on a program's needs, without affecting other workers. It is the application's responsibility to manage the worker pool.
-
Events
Description
Abstract: An asynchronous event-driven architecture in which certain kinds of objects ("emitters") periodically emit named events that cause listeners to be called.
EventEmitter calss: All objects that emit events are instances of the EventEmitter class.These objects expose an eventEmitter.on() that allow events to be handled by functions.
Listeners: When an EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously. Returned values are ignored.
-
-
-
-
Error Events
When an error occurs within an EventEmitter instance, typically an 'error' event is emitted. If no listener for 'error' is present, Node.js will exit if 'error' is emitted. Adding such listener is a best practice.
emitter.on('error', (err) => {
console.error('an error occured');
});
File System
Description
The module consists of simple wrappers around standard POSIX functions. All methods have synchronous and asynchronous form.
- Asynchronous form - a completion callback is always allowed as a last argument. First argument of the callback is always reserved for an exception. No guaranteed execution order exists.
- Synchronous form - Will block the entire process until completion. Exceptions are immediately thrown and can either be handled via try/catch block or left to bubble up.
-
-
FSWatcher class
-
Events
- change - Emitted when something changes in a watchted directory or file.
- error - Emitted when an error occurs.
ReadStream class
Events
- close - Emitted when the ReadStream's underlying file descriptor has been closed using the fs.close() method.
- open - Emitted when the ReadStream's file is opened.
Stream
Description
A stream is an abstract interface for working with streaming data in Node.js. Streams can be readable, writeable, or both. All streams are instances of EventEmitter
-
Writeable Streams
An abstraction for a destination to which data is written. All Writeable streams have the following usage pattern:
const writableStream = getWritableStreamSomehow();
writableStream.write('stuff');
writableStream.write('more stuff');
writableStream.end('done writing stuff');
DNS
Description
Contains functions belonging to two different categories:
1) Functions that use the underlying operating system facilities to perform name resolution. Contains only dns.lookup()
2) Functions that connect to an actual DNS server to perform name resolution and that always use the network to perform DNS queries.
-
HTTP
Description
Abstract: The HTTP interfaces in Node.js support many features of the protocol including large, possibly chunk-encoded messages. HTTP message headers are structured in a JSON-like way. Keys are lowercased.
Technical: In order to support the full spectrum of possible HTTP applications, Node.js's HTTP API is very low-level. It deals with stream handling and message passing only. Neither the headers, nor the body of a message are parsed.