fs built-in module of Node.js

fs (File system, file system) is a built-in module of node, which can be used to operate files in various operating systems (Windows, macOS, etc.). Check the official documentation of node, you can see that there are many APIs under the File system:

Some of them are used to read and write files, some are used to operate folders, etc., and they all provide three operation modes: synchronous , asynchronous and Promise . Here are some commonly used APIs as examples for illustration.

operation file

read file

synchronous read

fs.readFileSync()Used to read files synchronously (Sync), just pass in the path or file descriptor of the file to be read directly:

// 代码块 1.1.1
const fs = require('fs')
// 同步读取
const resSync = fs.readFileSync('./test.txt')
console.log(resSync)
console.log('看看会不会阻塞') 

The execution results are as follows. The printing of line 6 is after line 5, indicating that the synchronization operation will block the execution of subsequent codes:

resSyncThe result is a Buffer object , essentially binary content, just displayed in hexadecimal. If you want to see the text content, you can use toString()to : console.log(resSync.toString()), or fs.readFileSync()pass in the second parameter to - an optional object for specifying the configuration, which has 2 properties:

  • encoding, the default value is null, that is, the result is displayed as buffer, if you want to display the text, you can change it to 'utf-8'(or 'utf8');
  • flag, the default value when reading a file 'r', for more information about the flag, please refer to the official document .
// 代码块 1.1.2
const resSync = fs.readFileSync('./test.txt', {encoding: 'utf-8',flag: 'r'
})
console.log(resSync)
console.log('看看会不会阻塞') 

What you see resSyncnow is a string:

Asynchronous read - Callback

fs.readFile()It is used to read files asynchronously. It can pass in 3 parameters, the first two are fs.readFileSync()the same as , and the third parameter is a callback function, which is called when the reading result is obtained:

// 代码块 1.2.1
fs.readFile('./test.txt',{encoding: 'utf-8'},(err, data) => {if (!err) console.log(data)}
)
console.log('看看会不会阻塞') 

The execution results are as follows, and it can be seen that asynchronous reading will not block the execution of subsequent codes:

Asynchronous read - Promise

fs.promises.readFile()It is also used to read files asynchronously, but it can avoid the callback hell that is easy to generate when using the callback function to get the result:

// 代码块 1.3.1
fs.promises.readFile('./test.txt', {encoding: 'utf-8'}).then(res => {console.log(res)}).catch(err => console.log(err)) 

write to file

There are also synchronous and asynchronous methods for writing files. The asynchronous-callback api is used fs.writeFile()as an example below. Its first parameter can be the address or file descriptor of the file. If the file does not exist, it will be created; the second parameter is the content to be written; the third parameter is an optional object used to specify the configuration, Among them are the two attributes introduced before encodingand flag, but encodinghere the default value of is 'utf8', that is, the default written content will overwrite the original content, if you want to add to the original content, you can change it is (append); the fourth parameter is a callback function, which is called after the writing operation is completed. If an error occurs in writing, the error information will be passed in as a parameter:flag'w''a'

fs.writeFile('./test.txt','Hello Juejin',{encoding: 'utf8',flag: 'w'},err => {if (err) {console.log(err)return}console.log('写入成功')}
) 

file descriptor

As mentioned earlier, for the three methods of reading files, the first parameter passed in can also be a file descriptor (file descriptor) in addition to the path of the file. In a common operating system, the kernel maintains a table of currently open files and resources for each process, and each open file is assigned a simple number for identifying and tracking files, although different operations The specific implementation of the system may be different, but node handles the difference for us, assigning a number type file descriptor to each opened file.

We can get a file descriptor by fs.open()opening a file:

// 代码块 2.1.1
fs.open('./test.txt', (err, fd) => {if (!err) {console.log(fd)}
}) 

Looking at the type, you can know that its second parameter, that is, the callback function will be passed in two parameters, the first is the error message err, and the second is the file descriptor fd:

The result obtained is 3:

view file information

After getting the file descriptor, we can fs.fstat()view the file information through (the first parameter can only be fd):

fs.open('./test.txt', (err, fd) => {if (err) returnfs.fstat(fd, (err, stats) => {if (err) returnconsole.log(stats)fs.close(fd) // 关闭文件})
}) 

The printed results are as follows:

Action folder

create folder

The fs module can also operate on folders, for fs.mkdir()example you can create folders, and mkdir can be regarded as an abbreviation for make directory:

fs.mkdir('./test', err => console.log(err)) // 创建 test 文件夹 

read folder

fs.readdir()It can be used to read folders, and the callback function will return the files or folders contained in the read folder. For example, the structure of the node directory is shown in the following figure:

Execute the following code to read the node directory:

// fs.js
fs.readdir('../node', (err, files) => {if (!err) console.log(files)
}) 

The printed result is: [ 'fs.js', 'test', 'test.txt' ]. If you want to get more detailed information, you can pass in the configuration object and withFileTypesset to true:

fs.readdir('../node', { withFileTypes: true }, (err, files) => {if (!err) console.log(files)
}) 

Then the printed result will use the value Symbol(type)of to indicate whether it is a file (value 1) or a folder (value 2). For the introduction of Symbol, please refer to the detailed explanation of Symbol :

Now there is still a problem, that is, the index.txt file in the test folder has not been read. If you want to read all the files in the node directory, you can read it recursively:

function readDirRecursive(path) {fs.readdir(path, { withFileTypes: true }, (err, files) => {if (err) returnfiles.forEach(item => {if (item.isDirectory()) {readDirRecursive(`${path}/${item.name}`)} else {console.log(item.name)}})})
}
readDirRecursive('../node') 

We also need to withFileTypesset to true, so that the elements in the returned filesarray are objects, and there are nameproperties and isDirectory()methods to determine whether they are folders.

rename folder/file

fs.rename()Folders or files can be renamed, the first parameter is the old name, and the second parameter can pass the new name:

fs.rename('./test', './juejin', err => console.log(err)) 

at last

Recently, I also sorted out a JavaScript and ES note, a total of 25 important knowledge points, and explained and analyzed each knowledge point. It can help you quickly master the relevant knowledge of JavaScript and ES, and improve work efficiency.



Friends in need, you can click the card below to receive and share for free

Guess you like

Origin blog.csdn.net/Android_boom/article/details/129878924