Understanding and application of fs file system module in node.js

Foreword: Many friends are very distressed when learning node.js. This article will take you to easily understand the fs file system module.

Directory

1. Conceptual understanding

2. Read the contents of the specified file

2.1, Example 1: read file

2.2. Example 2: Judging whether the file is read successfully

3. Write to the file

3.1 Examples:

3.2, Example 4: Judging whether the writing is successful

4. The problem of fs module-route dynamic splicing

4.1. Solution 1: Provide the full path

4.2. Solution 2: Use __dirname

4.3, code demo

5. Practical exercises: Examination results arrangement

5.1. Requirements:

5.2. Steps:

1. Concept understanding

Definition: The fs module is a module officially provided by Node.js for operating files. It provides a series of methods and properties to meet the needs of users for file operations.

Two important methods:

  • The fs.readFile() method is used to read the contents of the specified file

  • The fs.writeFile() method is used to write content to the specified file

    const fs=require('fs')
    

Second, read the content in the specified file

2.1, Example 1: Read file

// 1. Import fs module to operate files, use fs to accept fs module
const fs = require('fs');
// After reading successfully
//2. Call the fs.readFile() method to read the file
// Parameter 1: The storage path of the read file
// Parameter 2: The encoding format is used to read the file, and utf-8 is generally specified by default
// Parameter 3: Callback function to get the results of read failure and success err (failed result) dataStr (successful result)
fs.readFile('./files/11.txt','utf-8', 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);
})

Run result:

2.2, Example 2: Judging whether the file is read successfully

Judging by the value of err

const fs = require('fs');
fs.readFile('./files/11.txt','utf-8', function(err,dataStr){
    if(err){
        return console.log('Failed to read file' + err.message)
    }
    console.log('read file successfully' + dataStr);
})

Run result:

3. Write to file

3.1 instance:

// 1. Import fs file system module
const fs = require('fs')
//2. Call the fs.writeFile() method to write the contents 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/11.txt','hello node.js', function(err){
    //2.1 If the file is written successfully, the value of err is equal to null
    // 2.2 If the file write fails, the value of err is equal to an error object
    console. log(err);
})

Run result:

3.2, Example 4: Judging whether the writing is successful

// 1. Import fs file system module
const fs = require('fs')
//2. Call the fs.writeFile() method to write the contents 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/11.txt','hello node.js', function(err){
    //2.1 If the file is written successfully, the value of err is equal to null
    // 2.2 If the file write fails, the value of err is equal to an error object
    // console. log(err);


    //Check if the file was successfully written
    if (err) {
      return console.log("Failed to read file" + err.message);
    }
    console.log("read file successfully");
})

operation result:

Four, fs module-routing dynamic splicing problem

When using the fs module to operate files, if the provided operation path is a relative path starting with / or ../, it is easy to have the problem of path dynamic splicing error. Reason: When the code is running, it will execute the node command The directory where it is located, and the full path of the operated file is dynamically spliced.

4.1, Solution 1: Provide the full path

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.

4.2, solution 2: use __dirname

__dirname indicates the directory where the current file is located and then character splicing

4.3, Code Demonstration

//Original method
const fs = require("fs");
fs.readFile("./files/11.txt", "utf-8", function (err, dataStr) {
  if (err) {
    return console.log("Failed to read file" + err.message);
  }
  console.log("read file successfully" + dataStr);
});
//Improve the method to provide a complete file storage path
// Pay attention to use the escape character \ otherwise the path cannot be read
const fs = require("fs");
fs.readFile("E: front end\\
odejsketangwangke\fs file system module\files\11.txt",
  "utf-8",
  function (err, dataStr) {
    if (err) {
      return console.log("Failed to read file" + err.message);
    }
    console.log("read file successfully" + dataStr);
  }
);
//Improvement method 2: __dirname indicates the directory where the current file is located, and then character splicing
const fs = require("fs");
fs.readFile(__dirname + "./files/11.txt","utf-8",function (err, dataStr) {
    if (err) {
      return console.log("Failed to read file" + err.message);
    }
    console.log("read file successfully" + dataStr);
  }
);

5. Practical practice: exam results arrangement

5.1, Requirement:

5.2, step:

5.3, code implementation

// 1. Import fs module to operate files, use fs to accept fs module
const fs = require("fs");
//2. Call the fs.readFile() method to read the file
fs.readFile("./files/chengj.txt", "utf-8", function (err, dataStr) {
  // 3. Determine whether the read is successful
  if (err) {
    return console.log("Failed to read" + err.message);
  }
// else {
// // return console.log("read successfully" + dataStr);
// }
  // 4.1 first divide the results and data according to spaces
  const arrOld = dataStr. split(" ");
  console.log(arrOld);
  // 4.2 Loop through the split array, and perform a string replacement operation on each item of data
  const arrNew = [];
  // For each item of data, replace the equal sign with a colon
  arrOld.forEach((item) => {
    arrNew.push(item.replace("=", ":"));
  });
// 4.3 Merge each item in the new array to get a new string
  const newStr=arrNew.join('\r\\
')
  console. log(newStr);
// 5. Call the fs.writeFile() method to write the processed results into a new file
fs.writeFile('./files/chengji-ok.txt', newStr, function(err){
    if(err){
        return console.log('Failed to write file!' + err.message);
    }
    console.log('scores written successfully!');
})
});

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Vue entry skill tree Node.js and npmNode installation and configuration