fs module

First, let's create a basic example of accessing the filesystem and opening a file, adding some text to it, closing the file, and then appending some more text to it. This would look similar to the following:

import { promises } from 'fs';

(async() => {
await promises.writeFile('example2.txt', "Here is some text ");
const fd = await promises.open('example2.txt', 'a');
await fd.appendFile("Here is some more text ");
await fd.close();
console.log(await promises.readFile('example2.txt', 'utf8'));
})();

First, we are grabbing the promise-based version of the library. Most of the built-in modules have a promise-based version, which can lead to nice-looking code, especially compared to the callback system. Next, we write to a file and give it some text. The writeFile method allows us to write to a file and create the file if it doesn't exist. After this, we open up FileHandle for our file.

Node.js took the POSIX style of I/O. This means that everything is treated like a file. In this case, everything is assigned a file descriptor (fd). This looks like a number to us in languages such as C++. After, we can pass this number to a variety of file functions that are available to us. Node.js, in the promises API, decided to switch to a FileHandle object, which is what we get instead of this file descriptor. It leads to cleaner code and a layer of abstraction over the system that is sometimes needed.

The a that we can see as the second argument states how we are going to use the file. In this case, we are going to append to the file. If we opened it with r, this means that we want to read from it, while if we opened it with w, this means that we want to overwrite whatever is already there.

Having an understanding of a Unix system can go a long way to understanding how Node.js works and how all of this corresponds to the programs that we are trying to write.

Then, we append some text to the file and close it. Finally, we console log whatever is in the file and state that we want to read it in as UTF-8 text instead of in binary.

There are many more APIs associated with the filesystem, and it is recommended to go through the promise documentation to see what capabilities we have, but they all boil down to us having access to the filesystem and being able to read/write/append to various files and directories. Now, let's move on to the net module.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.96.155