Home >Web Front-end >JS Tutorial >NodeJS study notes FS file module_node.js
1, opening analysis
The file system module is a simple wrapper for a set of standard POSIX file I/O operation methods. The module can be obtained by calling require("fs"). All methods in the file system module have asynchronous and synchronous versions.
(1), the asynchronous method in the file system module requires a completion callback function as the last incoming formal parameter.
(2), the composition of the callback function is determined by the asynchronous method called. Usually, the first formal parameter of the callback function is the returned error information.
(3), if the asynchronous operation is executed correctly and returned, the error parameter will be null or undefined. If you are using the synchronous version of the operation method, if an error occurs, the error will be returned in the form of a normal thrown error.
(4), you can use try and catch statements to intercept errors and allow the program to continue.
Let’s look at a simple example first, reading a file ("bb.txt"):
(1), create the file "bb.txt" with the following content ("Hello everyone, I am Nobita! (*^__^*) Hee hee...").
(2), the file reading operation is as follows:
Run result:
What should be noted here is: the encoding must be set when reading files, otherwise it will appear in the form of "buffer" by default.
Looking at the running effect without settings, the difference is still obvious. As follows:
Let’s do another write operation, as follows:
Run result:
Listing some commonly used examples:
2. The connection between Fs and Stream
"Stream" has asynchronous characteristics. We can divide a file or a piece of content into unknown "chunks" of a specified size for reading, and each time a "chunk" is read, we output it. until the file is read. This is like "Transfer-Encoding: chunked" supported by "http1.1". ("chunk" can exist in any form, NodeJS exists in the form of "Buffer" by default, which is more efficient). "Stream" in NodeJS has a super feature on Unix systems ("pipe" ------ pipe).
Do you still remember the first NodeJS program in "Http module article", "Hello, Big Bear!"? Let’s make some modifications based on that small program, as follows:
(1), create "bb.html"