Home  >  Article  >  Web Front-end  >  How does Node.js use the file system module? Introduction to commonly used fs module methods

How does Node.js use the file system module? Introduction to commonly used fs module methods

青灯夜游
青灯夜游forward
2021-08-06 10:04:532785browse

This article takes you through the file system module in Node.js, introduces how to use the file system module (fs module), and introduces some of the most common and useful fs methods.

How does Node.js use the file system module? Introduction to commonly used fs module methods

The file system module (fs for short) allows us to access and interact with the file system on our computer. [Recommended learning: "nodejs Tutorial"]

Using the fs module, we can perform the following operations:

  • Create files and directories
  • Modify files and directories
  • Delete files and directories
  • Read the contents of files and directories
  • ...

Suggestion: The file system module is relatively complex. It is recommended to check the official documentation, you can see all the methods.

This article will introduce you to the most common and useful fs methods. Without further ado, let’s see what these methods are.

How to use fs

The filesystem 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 at the top of the file add:

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 For safety reasons, 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 required. But it helps us a lot!

Synchronization and asynchronous

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.

Write File

To write a file from a Node.js application, use the writeFile method.

writeFile The method accepts at least the following parameters:

  • File name
  • Content
  • Callback

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:

  • fs.writeFileSync — Write files synchronously
  • fsPromises.writeFile — Write a file using a Promise-based API
Check out this gist: https://gist.github.com/catalinpit/571ba06c06214b5c8744036c6500af92

Reading from a file

Before reading a file, the path to the file needs to be created and stored.

path The module's path is convenient here.

Using the

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.

Write the following code in the file:

fs.readFile(filePath, (error, content) => {
  if (error) throw error

  process.stdout.write(content)
})

readFile The method accepts at least two parameters:

    The path to the file
  • Callback
If there is an error, it will throw an error. Otherwise, it prints the file contents in the terminal.

readFile There are other variations, such as:

  • fs.readFileSync — Write files synchronously
  • fsPromises.readFile — Write a file using a Promise-based API
Check out this gist: 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 方法向现有文件添加新内容。

如果比较 writeFileappendFile 这两种方法,我们可以发现它们是相似的。传递文件路径、内容和回调。

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!')
})

上面的代码片段演示了如何向现有文件添加新内容。如果运行应用程序并打开文件,您应该会看到其中的新内容。

查看此要点:https://gist.github.com/catalinpit/7c8d40db53dea9e6831f9ee89d92475c

原文地址:https://juejin.cn/post/6991848361527607327

作者:lio_zero

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of How does Node.js use the file system module? Introduction to commonly used fs module methods. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete