fs file system module in node.js

What is the fs filesystem module

The fs module is an official module provided by Node.js for manipulating files. It provides a series of methods and properties to meet the needs of users for file operations.

For example:

  • fs.readFile() method, used to read the contents of the specified file
  • fs.writeFile() method, used to write content to the specified file

Syntax format of fs.readFile()

Use the fs.readFile() method to read the contents of the specified file , the syntax format is as follows:

Interpretation of parameters:

  • Parameter 1: Mandatory parameter, string, indicating the path of the file.
  • Parameter 2: Optional parameter, indicating what encoding format to read the file in.
  • Parameter 3: Required parameter. After the file is read, the read result is obtained through the callback function

Syntax format of fs.writeFile()

Use the fs.writeFile() method to write content to the specified file . The syntax is as follows:

Interpretation of parameters:

  • Parameter 1: Required parameter, you need to specify a string of file path, indicating the storage path of the file.
  • Parameter 2: Required parameter, indicating the content to be written.
  • Parameter 3: Optional parameter, which indicates the format to write the file content in, and the default value is utf8.
  • Parameter 4: Required parameter, the callback function after the file is written.

Organize grade cases

There is a score.txt file in the disk, the content is as follows

 Organize the contents into the following format and write to a new file

 code show as below:

//1.导入fs模块
const fs = require('fs')

//2.调用fs.readFile()读取文件的内容
fs.readFile('./成绩.txt','utf8',function(err,dataStr){

    //3.判断是否读取成功
    if(err){
        return console.log('读取文件失败',err.message)
    }

    //4.1先把成绩的数据按照空格进行分割
    const arrOld = dataStr.split(' ')

    //4.2循环分割后的数组,对每一项数据,进行字符串的替换操作
    const arrNew = []
    arrOld.forEach(item => {
        arrNew.push(item.replace('=',': '))
    })

    //4.3把新数组的每一项进行合并,得到一个新的字符串
    const newStr = arrNew.join('\r\n')

    //5.调用fs.writeFile()方法,把处理完毕的数据,写入到新文件中
    fs.writeFile('./成绩-ok.txt',newStr,function(err){
        if(err){
            return console.log(写入文件失败)
        }
        console.log('写入文件成功')
    })
})

 

 

Guess you like

Origin blog.csdn.net/weixin_51382988/article/details/128556675