Node Ecosystem Readings - 401-advanced-javascript-v/seattle-javascript-401d29 GitHub Wiki
One of the most commonly used built-in modules in Node is the fs module
Node will assume you are interested in the binary data and will give you a Buffer object instead of a string. This is
an array-like object that contains numbers representing the bytes (8-bit chunks of data) in the files.
const {readFile} = require("fs");
readFile("file.txt", (error, buffer) => {
if (error) throw error;
console.log("The file contained", buffer.length, "bytes.",
"The first byte is:", buffer[0]);
});
There is an object
promises exported from the fs package since version 10.1 that contains most
of the same functions as fs but uses promises rather than callback functions.
const {readFile} = require("fs").promises;
readFile("file.txt", "utf8")
.then(text => console.log("The file contains:", text));
Another central module is called http.
To act as an HTTP client, we can use the request function in the http
module.
const {request} = require("http");
let requestStream = request({
hostname: "eloquentjavascript.net",
path: "/20_node.html",
method: "GET",
headers: {Accept: "text/html"}
}, response => {
console.log("Server responded with status code",
358
response.statusCode);
});
requestStream.end();