Using the Node.js API
Node.js replaces the API provided by the browser with one that supports common server-side tasks, such as processing HTTP requests and reading files. Behind the scenes, Node.js uses native threads, known as the worker pool, to perform operations asynchronously.
To demonstrate, Listing 4.10 uses the Node.js API to read the contents of a file.
Listing 4.10: Using the Node.js API in the handler.ts File in the src Folder
import { IncomingMessage, ServerResponse } from "http";
import { readFile } from "fs";
export const handler = (req: IncomingMessage, res: ServerResponse) => {
readFile("data.json", (err: Error | null, data: Buffer) => {
if (err == null) {
res.end(data, () => console.log("File sent"));
} else {
console.log(`Error: ${err.message}`);
res.statusCode = 500;
res.end();
}
});
};
As its name suggests, the readFile...