Node.js about fs, path, http module

1. First understand

Node.js is a JavaScript runtime environment based on the Chrome V8 engine. As a JavaScript runtime environment, Node.js only provides basic functions and APIs. However, based on these basic functions provided by Node.js, many powerful tools and frameworks have sprung up one after another, so learning Node.js can make front-end programmers competent for more jobs and positions.

2. fs 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.

node.js  ----fs模块----系统文件操作模块
1.fs.stat  检测是文件还是目录(目录 文件是否存在)
2.fs.mkdir  创建目录 (创建之前先判断是否存在)
3.fs.writeFile  写入文件(文件不存在就创建,但不能创建目录)
4. fs.appendFile 写入追加文件(末尾追加)
5.fs.readFile 读取文件
6.fs.readdir 读取目录
7.fs.rename 重命名
8.fs.rmdir  删除目录

①fs.readFile

fs.readFile('parameter 1'[, 'parameter 2'], parameter 3)
fs.readFile(“./demo.txt”, “utf-8”, (err, data) => {}
parameter 1: required Optional parameter, string, indicating the path of the file.
Parameter 2: Optional parameter, indicating the encoding format to read the file, usually utf-8 encoding.
Parameter 3: Required parameter, after the file is read, it will be called back The function gets the read result.

const fs = require('fs');
fs.readFile('./demo1.txt', 'utf-8', (err, dataStr) => {
    
    
if (err) {
    
    
return console.log('读取文件失败', err.message);
}
console.log('读取文件成功', dataStr);
});

②fs.writeFile

fs.writeFile(parameter 1,parameter 2[,parameter 3],parameter 4)
parameter 1: mandatory parameter, 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.

const fs = require('fs');
fs.writeFile('./demo2.txt', '123456', (err) => {
    
    
if (err) {
    
    
return console.log('写入失败', err.message);
}
console.log('写入成功');
});

③First experience of fs module

//1导入fs模块对象
const fs = require("fs");
// node fs.js
// console.log(fs);
//2操作系统文件
//2.1 读取文件内容
fs.readFile("./demo.txt", "utf-8", (err, data) => {
    
    
  // err为null,代表读取成功
  if (err) {
    
    
    console.log("失败");
  } else {
    
    
    console.log("成功" + data);
  }
});
//2.2写入文件内容
const text = "追加";
fs.appendFile("./demo.txt", text, (err) => {
    
    
  if (err) {
    
    
    return console.log("写入失败", err.message);
  }
  console.log("写入成功");
});

//2.3检测当前文件目录是否存在
fs.stat("./files", (err, stats) => {
    
    
  if (err) {
    
    
    // 如果不存在,则创建新的文件目录之后,再写入数据
    fs.mkdir("./files", () => {
    
    
      console.log("创建files文件夹成功");
      newFile();
    });
  } else {
    
    
    newFile();
  }
});

const newFile = () => {
    
    
  fs.appendFile("./files/demo2.txt", text, "utf-8", (err) => {
    
    
    if (!err) {
    
    
      console.log("写入成功!");
    }
  });
};

④ Splicing and importing of the first experience of fs module

//1导入fs模块对象
const fs = require("fs");
const path = require("path");
let dataArr = "";
let dataArr2 = "";
fs.readFile("./demo.txt", "utf-8", (err, data) => {
    
    
  dataArr = data.split(" ").join("\r\n");
  fs.readFile("./demo2.txt", "utf-8", (err2, data2) => {
    
    
    data = data + " " + data2;
    dataArr2 = data.split(" ").join("\r\n");
    fs.writeFile("./demo3.txt", dataArr2, (err) => {
    
    });
  });
  // __dirname 当前文件的绝对路径
  const fliePath = path.join(__dirname, "/demo3.txt");
  const fliePath2 = path.basename(__dirname + "/demo3.txt", ".txt");
  const fliePath3 = path.extname(__dirname + "/demo3.txt");

  fs.writeFile(fliePath, dataArr, (err) => {
    
    
    if (!err) {
    
    
      console.log("写入成功!");
    }
  });
  //   dataArr = data.split(" ")
});

3. path module

The path module is a module officially provided by Node.js to handle paths. It provides a series of methods and attributes
to meet the user's processing of paths

①path.join

path.join([…paths])
…paths sequence of path segments
Return Value:

const path = require('path');
const pathstr = path.join('/a', '/b/c', '../', './d', 'e');
console.log(pathstr); //输出\a\b\d\e
const pathStr2 = path.join(__dirname, './files/demo1.txt ');
console.log(pathStr2); //输出 当前文件所在目录\files\demo1.txt

②path.basename

path Mandatory parameter, representing a path string
ext Optional parameter, representing the file extension
Return: Represents the last part of the path

const path = require('path');
const fpath = '/a/b/c/index.html'; //文件的存放路径
var fullName = path.basename(fpath);
console.log(fullName); //输出index.html
var namewithoutExt = path.basename(fpath, '.html');
console.log(namewithoutExt); //输出index

③path.extname(path)

path is a required parameter, a string representing a path
Return: Returns the obtained extension string

const path = require('path');
const fpath = '/a/b/c/index.html'; //路径字符串
const fext = path.extname(fpath);
console.log(fext); //输出.html

④path module experience

//1导入fs模块对象
const fs = require("fs");
const path = require("path");
let dataArr = "";
let dataArr2 = "";
fs.readFile("./demo.txt", "utf-8", (err, data) => {
    
    
  dataArr = data.split(" ").join("\r\n");
  fs.readFile("./demo2.txt", "utf-8", (err2, data2) => {
    
    
    data = data + " " + data2;
    dataArr2 = data.split(" ").join("\r\n");
    fs.writeFile("./demo3.txt", dataArr2, (err) => {
    
    });
  });
  // __dirname 当前文件的绝对路径
  const fliePath = path.join(__dirname, "/demo3.txt");
  const fliePath2 = path.basename(__dirname + "/demo3.txt", ".txt");
  const fliePath3 = path.extname(__dirname + "/demo3.txt");

  fs.writeFile(fliePath, dataArr, (err) => {
    
    
    if (!err) {
    
    
      console.log("写入成功!");
    }
  });
  //   dataArr = data.split(" ")
});

4. http module

The http module is a module officially provided by Node.js to create a web server. Through
the http.createServer() method provided by the http module, an ordinary computer can be conveniently turned into a web server to provide web resource services to the outside world

① http general use

//部署node本地服务器
//1.导入http模块
const http = require("http");
// console.log(http);
//2.创建web服务器实例
const server = http.createServer();
//3.为服务器实例绑定request事件,监听客户端请求
//req 客服端请求响应  req.url  req.method
//res 服务端请求响应  res.end()
server.on("request", (req, res) => {
    
    
  console.log("服务器请求");
  //发送的内容包含中文
  const str = `您请求的url地址是 ${
      
      req.url}---请求的 method类型是${
      
      req.method}`;
  //为了防止中文显示乱码的问题,需要设置响应头Content-Type 的值为text / html;charset = utf - 8;
  res.setHeader("Content-Type", "text/html;charset=utf-8");
  //把包含中文的内容,响应给客户端
  res.end(str);
});
//4.启动服务器
server.listen(80, () => {
    
    
  console.log("服务器启动了http://127.0.0.1:80 ");
});

② Respond to different html content according to different urls

// 根据不同的 url 响应不同的 html 内容
// 1.导入http,fs,path模块
const http = require("http");
const fs = require("fs");
const path = require("path");
// 2.创建nodejs服务器实例对象
const server = http.createServer();

// 3.绑定request事件,监听客户请求行为
server.on("request", (req, res) => {
    
    
  // 3.1 获取URL地址
  const url = req.url;
  console.log(url);
  let content = "";
  // 3.3 读取页面数据
  let pageUrl = path.join(__dirname, url);
  // 请求网址: http://127.0.0.1/clock/index.html
  if (url == "/") {
    
    
    pageUrl = path.join(__dirname, "/index.html");
  }
  //  读取clock/index.html页面数据
  fs.readFile(pageUrl, "utf-8", (err, dataStr) => {
    
    
    if (!err) {
    
    
      // 请求成功是响应的页面数据
      res.end(dataStr);
    } else {
    
    
      // 请求失败时响应的页面数据
      console.log("请求失败");
      content = "<h1>404 Not found!</h1>";
      res.end(content);
    }
  });
});

// 4.启动服务器
server.listen(80, () => {
    
    
  console.log("http://127.0.0.1");
});

おすすめ

転載: blog.csdn.net/z2000ky/article/details/129322924