Nodejs-fs file system module

Directory

1. What is the fs filesystem module

2. Read the contents of the specified file

1. Syntax format of fs.readFile()

2. Sample code for fs.readFile()

3. Determine whether the file is read successfully

3. Write content to the specified file

1. Syntax format of fs.writeFile()

2. Sample code for fs.writeFile()

3. Determine whether the file is written successfully

4. Practice Questions – Exam Results

1. Topic requirements

2. Core implementation steps

5. fs module – path dynamic splicing problem


1. What is the fs filesystem module

The fs module is a module officially 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

If you want to use the fs module to manipulate files in JavaScript code, you need to import it first in the following way:

2. Read the content of the specified file

1. 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.

2. Sample code for fs.readFile()

Read the content of the specified file in utf8 encoding format, and print the values of err and dataStr:

code:

// 1. Import fs module to operate files
const fs = require('fs')

// 2. Call the fs.readFile() method to read the file
// Parameter 1: The storage path of the read file
// Parameter 2: The encoding format used when reading the file, generally utf8 is specified by default
// Parameter 3: callback function to get the results of read failure and success err dataStr
fs.readFile('./files/11.txt', 'utf8', function(err, dataStr) {
  // 2.1 Print the failed result
  // If the read is successful, the value of err is null
  // If the reading fails, the value of err is an error object, and the value of dataStr is undefined
  console. log(err)
  console.log('-------')
  // 2.2 Print the successful result
  console. log(dataStr)
})

(1) If the file is read successfully, the value of err is null

(2) If the file reading fails, the value of err is an error object, and the value of dataStr is undefined

3. Determine whether the file is successfully read

You can judge whether the err object is null, so as to know the result of file reading:

code:

const fs = require('fs')

fs.readFile('./files/11.txt', 'utf8', function(err, dataStr) {
  if (err) {
    return console.log('Failed to read file!' + err.message)
  }
  console.log('read file successfully!' + dataStr)
})

(err is true to read failed, false to read successfully)

(1) File read successfully

(2) File reading failed

3. Write content to the specified file

1. 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.

2. Sample code for fs.writeFile()

Write the file content to the specified file path:

(1) If the file is written successfully, the value of err is equal to null

(2) If the file write fails, the value of err is equal to an error object

3. Determine whether the file is successfully written

You can judge whether the err object is null, so as to know the result of writing the file:

code:

// 1. Import fs file system module
const fs = require('fs')

// 2. Call the fs.writeFile() method to write the content of the file
// Parameter 1: Indicates the storage path of the file
// Parameter 2: Indicates the content to be written
// parameter 3: callback function
fs.writeFile('./files/3.txt', 'ok123', function(err) {
  // 2.1 If the file is successfully written, the value of err is equal to null
  // 2.2 If the file fails to be written, the value of err is equal to an error object
   // console. log(err)

  if (err) {
    return console.log('File writing failed!' + err.message)
  }
  console.log('The file was written successfully!')
})

(err is true, writing failed, false writing is successful)

(1) If the file is written successfully, return the file is written successfully!

(2) If the file writing fails, return the file writing failure plus an error message

4. Practice questions – Exam results arrangement

1. Topic requirements:

Use the fs file system module to organize the test data in the score.txt file under the material directory into the score-ok.txt file. Before sorting, the data format in the score.txt file is as follows:

After the sorting is completed, the data format in the expected result-ok.txt file is as follows:

2. Core implementation steps:

(1) Import the required fs file system module

(2) Use the fs.readFile() method to read the grade.txt file in the material directory

(3) Judging whether the file failed to be read

(4) After the file is read successfully, process the score data

(5) Call the fs.writeFile() method to write the completed score data into the new file score-ok.txt

code:

// 1. Import fs module
const fs = require('fs')

// 2. Call fs.readFile() to read the contents of the file
fs.readFile('../Material/Score.txt', 'utf8', function(err, dataStr) {
  // 3. Determine whether the read is successful
  if (err) {
    return console.log('Failed to read file!' + err.message)
  }
  // console.log('read file successfully!' + dataStr)
  
// 4. Process data
  // 4.1 First divide the score data according to spaces
  const arrOld = dataStr. split(' ')
  // Output [ 'Little Red=99', 'Little White=100', 'Little Yellow=70', 'Little Black=66', 'Little Green=88' ]
  // 4.2 Loop through the split array, and replace ":" with string "=" for each item of data
  const arrNew = []
  arrOld.forEach(item => {
    arrNew.push(item.replace('=', ':'))
  })
  // Output [ 'Little Red: 99', 'Little White: 100', 'Little Yellow: 70', 'Little Black: 66', 'Little Green: 88' ]
  // 4.3 Combine each item in the new array to get a new string
  const newStr = arrNew.join('\r\
') // arrNew.join splicing; \r\
 carriage return and line feed
  // output
  // Little Red: 99
  // Xiaobai: 100
  // little yellow: 70
  // Little Black: 66
  // little green: 88

  // 5. Call the fs.writeFile() method to write the processed results into a new file
  fs.writeFile('./files/grade-ok.txt', newStr, function(err) {
    if (err) {
      return console.log('Failed to write file!' + err.message)
    }
    console.log('Score written successfully!')
  })
})

Run the screenshot:

5. fs module – the problem of dynamic path splicing

When using the fs module to operate files, if the provided operation path is a relative path starting with ./ or ../, it is easy to cause path dynamic splicing errors.

Reason: When the code is running, it will use the directory where the node command is executed to dynamically splice out the full path of the operated file.

solution:

(1) Solution 1: When using the fs module to operate files, provide the complete path directly, and do not provide a relative path starting with ./ or ../, so as to prevent the problem of dynamic path splicing.

(2) Solution 2: __dirname indicates the directory where the current file is located, thus preventing the problem of dynamic path splicing.

code:

const fs = require('fs')

// The problem of path splicing error occurs because a relative path starting with ./ or ../ is provided
// If you want to solve this problem, you can directly provide a complete file storage path
/* fs.readFile('./files/1.txt', 'utf8', function(err, dataStr) {
  if (err) {
    return console.log('Failed to read file!' + err.message)
  }
  console.log('read file successfully!' + dataStr)
}) */

//Solution 1: Provide a complete file storage path directly. Portability is very poor, not conducive to maintenance
/* fs.readFile('C:\Users\Miriam\Desktop\web front-end development course\\
odejs\day1\code\files\1.txt', 'utf8', function(err , dataStr) {
  if (err) {
    return console.log('Failed to read file!' + err.message)
  }
  console.log('read file successfully!' + dataStr)
}) */

// Solution 2: __dirname indicates the directory where the current file is located
// console. log(__dirname)

fs.readFile(__dirname + '/files/1.txt', 'utf8', function(err, dataStr) {
  if (err) {
    return console.log('Failed to read file!' + err.message)
  }
  console.log('read file successfully!' + dataStr)
})