Basic application of fs module of Nodejs

The fs module is a built-in module for file system operations in Node.js, which provides various methods and functions for handling files and directories.

Table of contents

1. Write to file

2. Talk about synchronous and asynchronous

3. Additional write

4. Read the file

5. File renaming and file movement

6. File deletion

7. Folder operation


1. Write to file

Ordinary write method:

The fs.writeFile() and fs.writeFileSync() of the fs module are used,其中前者是异步方法,后者是同步方法。

语法格式:下面的代码执行会找到对应的文件写入str字符串,如果没有该文件,则会自动创建文件并写入,但是这种写入会将原来的文件直接覆盖掉。

异步方法:

const fs = require('fs')
let str = 'hello'
//会直接覆盖写入,如果没有文件夹会自动创建新的文件夹
fs.writeFile('1.txt', str, (err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('写入成功1')
})

Synchronization method:

Because the synchronous method has no error callback function, here we need to manually receive the error

const fs = require('fs')
try {
  fs.writeFileSync('1.txt', '11223344')
  console.log('文件写入成功')
} catch (error) {
  console.error('文件写入失败:', error)
}

 Streaming writes:

const fs = require('fs')
let ws = fs.createWriteStream('1.txt')
ws.write('111\n')
ws.write('222\n')
ws.close()

 The difference between streaming write and normal write:

  1. Writing method: The common method of writing files is to load the data to be written into the memory at one time, and then write the entire data block to the file. The stream writing method is to gradually write data to the file, and only write a small part of the data at a time.

  2. Memory usage: The common method of writing files needs to load all the data into memory before writing data, so when writing a large amount of data, it may take up more memory. However, the stream writing method writes data step by step, and only needs a small part of the data to be stored in the memory, so it occupies less memory.

  3. Scalability: The ordinary file writing method is suitable for writing small data volumes, while the streaming file writing method is suitable for scenarios with large data volumes or real-time writing. Streaming writes can write data to files in real time, and is suitable for processing large files or situations that require continuous writing, such as loggers or real-time data streams.

  4. Performance and efficiency: The common method of writing files may have a long waiting time when writing a large amount of data, because all data needs to be written at once. The stream writing method achieves real-time writing by gradually writing data streams, and has better performance and efficiency when processing large amounts of data.

To sum up, the ordinary method of writing to a file is suitable for one-time writing of a small amount of data, while the method of streaming to a file is suitable for situations where a large amount of data needs to be processed or written in real time. Streaming writing to files can provide better performance and scalability, and consume less memory when the amount of data is large.

2. Talk about synchronous and asynchronous

You can actually see that one of the above writing methods is synchronous and the other is asynchronous. What is the difference between them, or when should I use them?

Implementation process:

Everyone should be aware of the execution flow of js code, which is executed sequentially from top to bottom. This is the case with synchronization. It is executed in sequence, that is, when calling a synchronization method, the program will wait for the method to complete before continuing to execute. a statement. An asynchronous method, on the other hand, is non-blocking, returning immediately without waiting for the operation to complete. An asynchronous method usually accepts a callback function or returns a Promise object. When the operation is completed, the result will be processed through the callback function or the Promise processing mechanism.

We can see the execution flow through the following code example 

const fs = require('fs')
let str = 'hello'
//会直接覆盖写入,如果没有文件夹会自动创建新的文件夹
fs.writeFile('1.txt', str, (err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('异步写入成功')
})

try {
  fs.writeFileSync('1.txt', '11223344')
  console.log('同步写入成功')
} catch (error) {
  console.error('文件写入失败:', error)
}

console.log('全部代码执行完毕')

 

It can be seen that the following code is executed after the synchronous writing is completed, and the asynchronous method is executed last, and it will not affect the execution process of the entire code. From this, we can make an assumption that if the file we write is very large, Using a synchronous method will temporarily block the code, but asynchronous will not have such a problem.

It can be concluded from this that the synchronous method can be more convenient and intuitive, especially in simple scripts or programs with relatively simple processing logic, but if you are dealing with large files, it is recommended to use the asynchronous method.

3. Additional write

Async method:

Our previous written files are overwritten and written. After execution, the previous files will be overwritten. To implement additional writing, the following method is required, where \r\n means newline

const fs = require('fs')
fs.appendFile('1.txt', '\r\n111', (err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('追加成功')
})

Synchronization method:

try {
  fs.appendFileSync('1.txt', '\r\n222')
  console.log('同步追加成功')
} catch (error) {
  console.error('文件写入失败:', error)
}

4. Read the file

Reading files is also synchronous and asynchronous

const fs = require('fs')
//异步读取
fs.readFile('./1.txt', (err, data) => {
  if (err) {
    console.log(err)
    return
  }
  console.log(data.toString())
})
//同步读取
let data = fs.readFileSync('./1.txt', 'utf-8')
console.log(data.toString())

Streaming read:

const fs = require('fs')
let rs = fs.createReadStream('./1.txt')
rs.on('data', (chunk) => {
  console.log(chunk.toString())
})
rs.on('end', () => {
  console.log('读取完成')
})
rs.on('error', (err) => {
  console.log(err)
})

The most significant difference between streaming reading and ordinary reading methods is still the issue of speed

5. File renaming and file movement

file rename

const fs = require('fs')
fs.rename('./1.txt', './修改.txt', (err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('重命名成功')
})

file movement

In fact, the method of renaming is used to move the position


fs.rename('./修改.txt', '../test/1.txt', (err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('重命名成功')
})

6. File deletion

Both methods are available

const fs = require('fs')
fs.unlink('./2.txt', (err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('删除成功')
})

fs.rm('./1.txt', (err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('删除成功')
})

7. Folder operation

create folder

const fs = require('fs')
fs.mkdir('./html', (err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('创建成功')
})

Create recursively, that is, create a folder with a multi-layer structure

const fs = require('fs')
//递归创建

fs.mkdir('./a/b/c', { recursive: true }, (err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('创建成功')
})

 Read the content of the folder directory

const fs = require('fs')
//读取文件夹
fs.readdir('../fs模块', (err, files) => {
  if (err) {
    console.log(err)
    return
  }
  console.log(files)
})

operation result

 Delete folders (only single-level folders can be deleted)

//删除文件夹
fs.rmdir('./html', (err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('删除成功')
})

Recursively delete folders in a multi-level structure

const fs = require('fs')
//递归删除 官方不建议使用此方法,未来会被删除
fs.rmdir('./html', { recursive: true }, (err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('删除成功')
})

//官方建议删除方法
fs.rm('./a', { recursive: true }, (err) => {
  if (err) {
    console.log(err)
    return
  }
  console.log('删除成功')
})

Guess you like

Origin blog.csdn.net/m0_64642443/article/details/132083945