Home > Article > Web Front-end > What is the fs module in node
In node, the fs module refers to the "file system module", which is a module used to operate files. Most APIs of the fs module provide three operating methods: 1. Synchronous file operation: the code will be blocked and will not continue to execute; 2. Asynchronous callback function operation file: the code will not be blocked and a callback function needs to be passed in. When the When the result is generated, the callback function is executed; 3. Asynchronous Promise operation file: the code will not be blocked, and a Promise will be returned by calling the method operation through fs.promises.
The operating environment of this tutorial: Windows 7 system, nodejs version 16, DELL G3 computer.
The file system module (fs for short) allows us to access and interact with the file system on our computer.
fs module is a module officially provided by Node.js for operating files. It provides a series of methods and properties to meet users' file operation needs.
fs.readFile() method, used to read the contents of the specified file
fs.writeFile() method, used to If you want to write content to the specified file in JavaScript code
The file system module is a core Node.js module. This means we don't have to install it. The only thing we need to do is import the fs module into its own file.
So, add at the top of the file:
const fs = require('fs')
Now we can call any method from the file system module using the prefix fs .
Alternatively, we can just import the required methods from the fs API as follows:
const { writeFile, readFile } = require('fs')
Note: For convenience, we also need to import the path module. It is another core Node.js module that allows us to work with file and directory paths.
After importing the fs module, add in the file:
const path = require('path')
When using the file system module, the path module is not necessary. But it helps us a lot!
The file operations of the fs module generally support both synchronous and asynchronous APIs, and asynchronous also includes callback functions and promsie forms. Synchronization is usually followed by the word sync.
Most of the APIs of the fs module provide three operation methods:
Synchronous operation of files: the code will be blocked and will not continue to execute
Asynchronous callback function operation file: the code will not be blocked, the callback function needs to be passed in. When the result is obtained, the callback function will be executed
Asynchronous Promise operation file: the code will not Will be blocked. Calling method operation through fs.promises will return a Promise, which can be processed through then and catch.
It should be noted that by default, all fs methods are asynchronous. However, we can use the synchronized version by adding Sync at the end of the method.
For example, the synchronous version of the writeFile method is writeFileSync. Synchronous methods complete code synchronously, so they block the main thread. Blocking the main thread in Node.js is considered bad practice and we shouldn't do it.
Therefore, below we will all use the asynchronous method in the file system module.
To write a file from a Node.js application, use the writeFile
method.
writeFile
The method accepts at least the following parameters:
If the specified file already exists, it will replace the old content with the content you provide as an argument. If the specified file does not exist, a new file is created.
After importing the fs
and path
modules, write the following code in the file:
fs.writeFile('content.txt', 'All work and no play makes Jack a dull boy!', err => { if (err) throw err process.stdout.write('创建成功!') })
The above code will create a file named ## A new file of #content.txt and added the text
All work and no play makes Jack a dull boy! as content. If there are any errors, the callback function will throw that error. Otherwise, it will output to the console that the file was created successfully.
writeFile There are other variations, such as:
— Write files synchronously
— Write a file using the Promise-based API
Check out this gist: https://gist.github.com/catalinpit/571ba06c06214b5c8744036c6500af92Reading from a fileBefore reading a file, the path to the file needs to be created and stored.
path The module's path is convenient here.
path method in the
join module, you can create a file path like this:
const filePath = path.join(process.cwd(), 'content.txt')First parameter
process.cwd() Returns the current working directory. Now that you have the file path, you can read the file's contents.
fs.readFile(filePath, (error, content) => { if (error) throw error process.stdout.write(content) })
readFile The method accepts at least two parameters:
如果有错误,它会抛出一个错误。否则,它会在终端中输出文件内容。
readFile
还有其他变体,例如:
fs.readFileSync
— 同步写入文件fsPromises.readFile
— 使用基于 Promise 的 API 写入文件查看此要点:https://gist.github.com/catalinpit/badc2a539a44412892a0e05a9575d54d
在目录中显示文件与读取文件内容非常相似。但是,不是传递文件路径,而是传递当前工作目录(我们可以传递任何其他目录)。
然后,传递一个回调函数来处理响应。在文件中编写以下代码:
fs.readdir(process.cwd(), (error, files) => { if (error) throw error console.log(files) })
到目前为止,我们只使用 process.stdout.write
将内容输出到终端。但是,您可以简单地使用 console.log
,就像上面的代码片段一样。
如果运行该应用程序,我们应该会得到一个包含目录中所有文件的数组。
查看此要点:https://gist.github.com/catalinpit/f82c4e6ae3acd5d97efdecb0bc67979e
文件系统模块有一种方法,允许您删除文件。但是,需要注意的是,它只适用于文件,不适用于目录。
当以文件路径作为参数调用 unlink
方法时,它将删除该文件。将以下代码段添加到文件中:
fs.unlink(filePath, error => { if (error) throw error console.log('文件已删除!') })
如果您重新运行代码,您的文件将被删除!
查看此要点:https://gist.github.com/catalinpit/b1201434218c400f77e042109bfce99e
我们可以使用 mkdir
方法异步创建目录。在文件中编写以下代码:
fs.mkdir(`${process.cwd()}/myFolder/secondFolder`, { recursive: true }, (err) => { if (err) throw err console.log('已成功创建文件夹!') })
首先,要在当前工作目录中创建一个新文件夹。如前所述,您可以使用 cwd()
方法从 process
对象获取当前工作目录。
然后,传递要创建的一个或多个文件夹。但是,这并不意味着您必须在当前工作目录中创建新文件夹。你可以在任何地方创建它们。
现在,第二个参数是递归选项。如果未将其设置为 true
,则无法创建多个文件夹。如果将 recursive
选项设置为 false
,上述代码将给出一个错误。试试看!
但是,如果您只想创建一个文件夹,则无需将 recursive
选项设置为 true
。
以下代码可以正常工作!
fs.mkdir(`${process.cwd()}/myFolder`, err => { if (err) throw err console.log('已成功创建文件夹!') });
因此,我想强调使用 recursive
。如果要在文件夹中创建文件夹,则需要将其设置为 true
。它将创建所有文件夹,即使它们不存在。
另一方面,如果您只想创建一个文件夹,可以将其保留为 false
。
查看此要点:https://gist.github.com/catalinpit/09bad802541102c0cce2a2e4c3985066
删除目录的逻辑类似于创建目录。如果您查看为创建目录而编写的代码和下面的代码,您会发现相似之处。
因此,在文件中编写以下代码:
fs.rmdir(`${process.cwd()}/myFolder/`, { recursive: true }, err => { if (err) throw err console.log('已成功删除文件夹!') })
使用文件系统模块中的 rmdir
方法,并传递以下参数:
如果将 recursive
属性设置为 true
,它将删除文件夹及其内容。请务必注意,如果文件夹中包含内容,则需要将其设置为 true
。否则,您将得到一个错误。
以下代码段仅在文件夹为空时有效:
fs.rmdir(`${process.cwd()}/myFolder/`, err => { if (err) throw err console.log('已成功删除文件夹!') })
如果 myFolder
中有其他文件和/或文件夹,如果未传递 { recursive: true }
,则会出现错误。
知道何时使用 recursive
选项以及何时不避免问题是很重要的。
查看此要点:https://gist.github.com/catalinpit/a8cb6aca75cef8d6ac5043eae9ba22ce
使用 fs
模块,您可以重命名目录和文件。下面的代码片段显示了如何使用 rename
方法进行此操作。
// 重命名一个目录fs.rename(`${process.cwd()}/myFolder/secondFolder`, `${process.cwd()}/myFolder/newFolder`, err => { if (err) throw err console.log('目录重命名!') });// 重命名一个文件fs.rename(`${process.cwd()}/content.txt`, `${process.cwd()}/newFile.txt`, err => { if (err) throw err console.log('文件重命名!') });
rename
方法包含三个参数:
因此,要重命名文件或目录,我们需要传递当前文件/目录的名称和新名称。运行应用程序后,应更新目录/文件的名称。
需要注意的是,如果新路径已经存在(例如,文件/文件夹的新名称),它将被覆盖。因此,请确保不要错误地覆盖现有文件/文件夹。
查看此要点:https://gist.github.com/catalinpit/5c3e7c6ae39d09996ff67175a719122e
我们还可以使用 appendFile
方法向现有文件添加新内容。
如果比较 writeFile
和 appendFile
这两种方法,我们可以发现它们是相似的。传递文件路径、内容和回调。
fs.appendFile(filePath, '\nAll work and no play makes Jack a dull boy!', err => { if (err) throw err console.log('All work and no play makes Jack a dull boy!') })
上面的代码片段演示了如何向现有文件添加新内容。如果运行应用程序并打开文件,您应该会看到其中的新内容。
更多node相关知识,请访问:nodejs 教程!
The above is the detailed content of What is the fs module in node. For more information, please follow other related articles on the PHP Chinese website!