0% found this document useful (0 votes)
18 views4 pages

Node Is Asynchronous by Default and Buffers

Node.js operates on a single-threaded model that is asynchronous and non-blocking by default, allowing it to handle high levels of concurrency without the complexity of multithreading. It utilizes error-first callbacks for asynchronous operations, and developers can easily convert these to Promise-based functions using util.promisify() or async/await syntax. Additionally, Node's Buffer class is essential for handling binary data, providing methods for encoding and decoding strings into byte sequences with various character encodings.

Uploaded by

kilaruharika2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views4 pages

Node Is Asynchronous by Default and Buffers

Node.js operates on a single-threaded model that is asynchronous and non-blocking by default, allowing it to handle high levels of concurrency without the complexity of multithreading. It utilizes error-first callbacks for asynchronous operations, and developers can easily convert these to Promise-based functions using util.promisify() or async/await syntax. Additionally, Node's Buffer class is essential for handling binary data, providing methods for encoding and decoding strings into byte sequences with various character encodings.

Uploaded by

kilaruharika2003
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Node Is Asynchronous by Default

Node does not achieve concurrencywith threads. Multithreaded programming is


notoriously hard to do correctly, anddifficult to debug. Also, threads are a
relatively heavyweight abstraction and if youwant to write a server that can handle
hundreds of concurrent requests, using hundredsof threads may require a
prohibitive amount of memory. So Node adopts thesingle-threaded JavaScript
programming model that the web uses.
Node achieves high levels of concurrency while maintaining a single-
threaded programmingmodel by making its API asynchronous and nonblocking by
default. Some functions in Node’s API are synchronous but nonblocking: they run
to completionand return without ever needing to block.Node was created before
JavaScripthad a Promise class, so asynchronous Node APIs are callback-based.
Generally, the last argument you pass to an asynchronous Nodefunction is a
callback. Node uses error-first callbacks, which are typically invoked withtwo
arguments. The first argument to an error-first callback is normally null in thecase
where no error occurred, and the second argument is whatever data or responsewas
produced by the original asynchronous function you called.
The following code demonstrates how to use the nonblockingreadFile()
functionto read a configuration file, parse it as JSON, and then pass the parsed
configurationobject to another callback:
const fs = require("fs"); // Require the filesystem module
// Read a config file, parse its contents as JSON, and pass the
// resulting value to the callback. If anything goes wrong,
// print an error message to stderr and invoke the callback with null
function readConfigFile(path, callback) {
fs.readFile(path, "utf8", (err, text) => {
if (err) { // Something went wrong reading the file
console.error(err);
callback(null);
return;
}
let data = null;
try {
data = JSON.parse(text);
} catch(e) { // Something went wrong parsing the file contents
console.error(e);
}
callback(data);
});
}
It is easy to create Promise-based variants of its callback-basedAPIs using
the util.promisify() wrapper. Here’s how we could rewrite the readConfigFile()
function to return a Promise:
Const util = require("util");
const fs = require("fs"); // Require the filesystem module
const pfs = {
// Promise-based variants of some fs functions
readFile: util.promisify(fs.readFile)
};
functionreadConfigFile(path) {
returnpfs.readFile(path, "utf-8").then(text => {
returnJSON.parse(text);
});
}
We can also simpify the preceding Promise-based function using async and
await.
async function readConfigFile(path) {
let text = await pfs.readFile(path, "utf-8");
returnJSON.parse(text);
}
Buffers:-
One of the datatypes you’re likely to use frequently in Node—especially
when readingdata from files or from the network—is the Buffer class. A
Buffer is a lot like a string,except that it is a sequence of bytes instead of a
sequence of characters. Node was createdbefore core JavaScript supported typed
arrays and there was noUint8Array to represent an array of unsigned bytes. Node
defined the Buffer class tofill that need. Now that Uint8Array is part of the
JavaScript language, Node’s Bufferclass is a subclass of Uint8Array.
The bytes in a buffer can be initialized from characterstrings or
converted to character strings. A character encoding maps each characterin some
set of characters to an integer. Given a string of text and a characterencoding, we
can encode the characters in the string into a sequence of bytes. Andgiven a
sequence of bytes and a character encoding, we candecode those bytes into a
sequence of characters. Node’s Buffer class has methods thatperform both
encoding and decoding, and you can recognize these methods becausethey expect
an encoding argument that specifies the encoding to be used.
Encodings in Node are specified by name, as strings. The supported
encodings are:
"utf8":- This is the default when no encoding is specified, and is the
Unicode encodingyou are most likely to use.
"utf16le":- Two-byte Unicode characters, with little-endian ordering.
Codepoints above\uffff are encoded as a pair of two-byte sequences. Encoding
"ucs2" is an alias.
"latin1":- The one-byte-per-character ISO-8859-1 encoding that defines a
character setsuitable for many Western European languages.
In latin1 each character is exactly one byte long. In utf8 a character can
consist of more than one byte.
"ascii":- The 7-bit English-only ASCII encoding, a strict subset of the
"utf8" encoding.
"hex":- This encoding converts each byte to a pair of ASCII hexadecimal
digits.
"base64":- This encoding represents binary data in ASCII format.
Here is some example code that demonstrates how to work with Buffers and how
toconvert to and from strings:
let b = Buffer.from([0x41, 0x42, 0x43]); // <Buffer 41 42 43>
b.toString() // => "ABC"; default "utf8"
b.toString("hex") // => "414243"
let computer = Buffer.from("IBM3111", "ascii"); // Convert string to Buffer
for(let i = 0; i<computer.length; i++) { // Use Buffer as byte array
computer[i]--; // Buffers are mutable
}
computer.toString("ascii") //
computer.subarray(0,3).map(x=>x+1).toString() // => "IBM"
// Create new "empty" buffers with Buffer.alloc()
let zeros = Buffer.alloc(1024); // 1024 zeros
let ones = Buffer.alloc(128, 1); // 128 ones
let dead = Buffer.alloc(1024, "DEADBEEF", "hex");
// Repeating pattern of bytes
// Buffers have methods for reading and writing multi-byte values
// from and to a buffer at any specified offset.
dead.readUInt32BE(0)
dead.readUInt32BE(1)
dead.readBigUInt64BE(6)
dead.readUInt32LE(1020)

You might also like