Getting Started with Node.js - The fs Filesystem Module

1 Introduction

The content of this article comes from bilibili dark horse programmers

1.1 Why JavaScript can be executed in the browser?

There is a JS parsing engine in the browser
Chrome: V8
Firefox: OdinMonkey (Odin Monkey)
Safari: JSCore
IE: Charka (Chakra)

insert image description here

1.2 Why JavaScript can manipulate DOM and BOM

Every browser has built-in API functions such as DOM and BOM, so JavaScript in the browser can call them

insert image description here

1.3 JavaScript runtime environment in the browser

The operating environment refers to the necessary environment for the normal operation of the code.
The V8 engine is responsible for parsing and executing JavaScript code.
The built-in API is a special interface provided by the operating environment and can only be called in the operating environment to which it belongs.

insert image description here

1.4 Can JavaScript be used as a backend

Yes, Node.js provides a runtime environment

2 Introduction to Node.js

2.1 What is Node.js

Node official website

Node.js 是A Chrome V8-basedJavaScript运行环境

2.2 JavaScript runtime environment in Node.js

The browser is the front-end operating environment of JavaScript
Node.js is the back-end operating environment of JavaScript
In Node.js, DOM, BOM and other built-in browser APIs cannot be called

insert image description here

2.3 Node.js Learning Path

JavaScript learning path in the browser:
JavaScript basic syntax + browser built-in API (DOM + BOM) + third-party libraries (jQuery, art-template, etc.)

Node.js learning path:
JavaScript basic syntax + Nodejs built-in API modules (fs, path, http, etc.) + third-party API modules (express.mysal, etc.)

3 What is a terminal

The terminal is specially designed for developers as a way to realize human-computer interaction

Commonly used terminal commands:
tab: quickly complete the file path
esc: clear the current command (Ctrl + u)
cls: clear the current terminal (mac: clear)

4 fs file system module

4.1 What is the fs file system 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:
• The fs.readFile() method is used to read the contents of the specified file
• The fs.writeFile() method is used to write the contents 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:

const fs = require("fs");

4.2 fs.readFile()

fs.readFile(path[, options], callback)
Parameter 1: The storage path of the file
Parameter 2: The encoding format used when reading the file, optional, default utf8
Parameter 3: Callback function, get the success and failure of reading result

/// 1 导入 fs 模块
const fs = require("fs");

// 2 调用 fs.readFile() 读取文件
fs.readFile("./files/1.txt", "utf8", (err, dataStr) => {
    
    
  // 如果读取成功, err 值为 null
  // 如果读取失败, err 值为错误对象, dataStr 值为 undefined
  if (err) {
    
    
    return console.log("读取文件失败", err);
  }
  console.log("读取文件成功", dataStr);
});

4.3 fs.writeFile

fs.writeFile(path, data[, options], callback)
Parameter 1: file storage path
Parameter 2: content to be written
Parameter 3: encoding format used when writing the file, default utf8
Parameter 4: callback function, get write file result

// 1 导入 fs 模块
const fs = require("fs");

// 2 调用 fs.writeFile() 写入文件
fs.writeFile("./files/1.txt", "写入文件", (err) => {
    
    
  // 如果写入成功,err 值为 null
  // 如果写入失败,err 值为 错误对象
  if (err) {
    
    
    return console.log("写入文件失败", err);
  }
  console.log("写入文件成功", dataStr);
});

4.4 Exercises

Before finishing:

小红=99 小白=100 小黄=70 小黑=66 小绿=88

After finishing:

小红:99
小白:100
小黄:70
小黑:66
小绿:88

① Import the required fs file system module
② Use the fs.readFile() method to read the score txt file in the material directory
③ Determine whether the file fails to be read
④ After the file is read successfully, process the score data
⑤ Process the completed score data , call the ts.writeFile() method to write to the new file result-before.txt

const fs = require("fs");

fs.readFile("./files/成绩.txt", "utf8", (err, dataStr) => {
    
    
  if (err) {
    
    
    return console.log("读取文件失败");
  }
  const oldData = dataStr.replaceAll("=", ":").replaceAll(" ", "\n");
  fs.writeFile("./files/成绩-after.txt", oldData, (err) => {
    
    
    if (err) {
    
    
      return console.log("写入文件失败");
    }
    console.log("写入文件成功");
  });
});

4.5 Path 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 cause path dynamic splicing errors.

Reason: When the code is running, it will dynamically splice out the full path of the operated file based on the directory where the node command is executed. Solution:
When using the fs module to operate files, directly provide the full path instead of ./ or The relative path at the beginning of .../ prevents the problem of dynamic path splicing

// __dirname 表示当前执行脚本所在的目录
const fs = require("fs");
fs.readFile(__dirname + "/files/成绩.txt", "utf8");

Guess you like

Origin blog.csdn.net/weixin_36757282/article/details/127574640