node.js learning 2

Modular

  • The built-in module does not need to be installed, the external module needs to be installed;
    Insert picture description here
    this file is a custom module

Insert picture description here
require("./home");//The same level directory of the custom module needs to be added./

The file name built-in module of the following file

Insert picture description here

require("tt"); //Store in node_modules and execute according to the rules of built-in modules.

npm package manager (alias: module manager)

npm common commands:

  • npm init: guide to create a package.json file
  • npm root to view the path of the current package installation or through npm root -g to view the global installation path;
  • npm -v view version
  • node -v node version book
  • npm i jquery --save
  • npm i cookie client
  • npm i axios --save-dev
    npm i axios --save-dev This is the development dependency


"dependencies" in package.json : {//Run dependency
"jquery": "^3.6.0" //npm i jquery --save
},
"devDependencies": {}, //Development dependencies

npm install module_name -S or --save means npm install module_name --save write dependencies
npm install module_name -D or --save-dev means npm install module_name --save-dev write devDependencies

fs module

  • fs is a file operation module. All file operations are divided into synchronous and asynchronous. The characteristic is that synchronization will add "Sync", such as: asynchronous read file "readFile", synchronous read file "readFileSync";

A preliminary understanding of the fs module

//fs:操作文件的模块  内置模块
const fs = require("fs");

>  增删改查
1.  文件操作  2.  目录操作

1. File operation

  • Write file

writeFile(): Write file
Parameter 1: File name, including file format
Parameter 2: File, the content to be written

fs.writeFile("1.txt", "我是需要写入的文件", function(err) {
    
    
    if (err) {
    
    
        return console.log(err); //输出报错信息
    }
    console.log("写入成功");
});

When the written file exists, the original file content will be overwritten and
{flag:"a"}
parameters will also be {flag:"a"} parameter 3. Configuration object {}: flag attribute: a is appended write
w: write (default value)
r: Read

fs.writeFile("1.txt", "我是追加进来的内容", {
    
     flag: "w" }, function(err) {
    
    
    if (err) {
    
    
        return console.log(err); //输出报错信息
    }
    console.log("写入成功");
});

File read fs.readFile

冷门方式
fs.readFile("1.txt",(err,data)=>{
    
    
    if(err){
    
    
        return console.log(err);
    }
    console.log(data.toString());
})



fs.readFile():
回调函数中  参数1:错误的信息
"utf-8"
fs.readFile("1.txt", "utf-8", (err, data) => {
    
    
    if (err) {
    
    
        return console.log(err);
    }
    console.log(data);
})
所有的文件操作,默认都有同步和异步;
默认是同步的,需要异步的话,在方法名前加Sync
例如:readFileSync();
 fs.readFileSync("1.txt", "utf-8");
 console.log(data);

// let data = fs.readFileSync("1.xtx").toString();
// console.log(data);

/Change file name: Rename
//Parameter 1: Original file name
//Parameter 2: New file name

 fs.rename("1.txt", "11.txt", err => {
    
    
     if (err) {
    
    
         return console.log(err);
     }
     console.log("修改成功");
 });

Delete file – fs.unlink("")

fs.unlink("2.txt", err => {
    
    
    if (err) {
    
    
        return console.log(err);
    }
    console.log("删除成功");
})

Copy files

fs.copyFile();
1.本质是先读取,再写入
fs.copyFile("11.txt", "aa.txt", err => {
    
    
    if (err) {
    
    
        return console.log(err);
    }
    console.log("复制成功");
})

2.封装复制
function myCopyFile(src, dest) {
    
    
    fs.writeFileSync(dest, fs.readFileSync(src));
}
myCopyFile("11.txt", "4.txt");

2: Directory operation

No suffix format is required when manipulating directories

创建目录
fs.mkdir("ding", err => {
    
    
    if (err) {
    
    
        return console.log(err);
    }
    console.log("创建成功");
})
修改目录名称
fs.rename("ding", "da", err => {
    
    
    if (err) {
    
    
        return console.log(err);
    }
    console.log("修改成功");
})
读取目录
fs.readdir("da", (err, data) => {
    
    
    if (err) {
    
    
        return console.log(err);
    }
    console.log(data);//读出来的是一个数组
})
删除目录(空目录/空文件夹)
fs.rmdir("da", err => {
    
    
    if (err) {
    
    
        return console.log(err);
    }
    console.log("删除成功");
})


判断文件或目录是否存在
fs.exists("5.txt", function(exists) {
    
    
    console.log(exists); //是否找到指定内容  找到就是true找不到就是false
})
//获取文件或目录的详细信息
fs.stat("http.html", (err, data) => {
    
    
    if (err) {
    
    
        return console.log(err);
    }
    console.log(data);

// //Is it a file
// let res = data.isFile();
// console.log(res);
// //Is it a directory
// data.isDirectory();
})

Delete non-empty directories

Ideas: 1. Delete the files in the directory first.
2. When you know that the directory is empty, delete the directory directly

function removerDir(path) {
    
    
    //获取目录
    let data = fs.readdirSync(path);
    //["a",2.html","3.txt","4.txt"]
    // console.log(data)

    //总体思路
    for (let i = 0; i < data.length; i++) {
    
    
        //循环判断目录中的每一个内容

        //处理子目录的路径
        let url = path + "/" + data[i];
        /*
         循环1: url =  "22/a"
         循环2:下来就是a文件  然后时a文件下面的所有内容

         */
        //获取详细信息
        let stat = fs.statSync(url);
        console.log(stat.isDirectory());
        if (stat.isDirectory()) {
    
     //如果是目录  继续查找
            removerDir(url);
        } else {
    
     //文件,删除
            fs.unlinkSync(url); //   path  =  22

        }
    }
    //当循环结束后,目录成为空目录
    fs.rmdirSync(path);
}
//注意事项:在使用node.js删除文件时,不会经过回收站
//          在删除前,  切记备份
//          一面删除错误,发生不可挽救的损失
removerDir("22");

Pay special attention to these two places
Insert picture description here

The buffer of buffer buffer data is also a class, not a module
  • The way it is created now
  • Parameters: is the size of the content, in bytes

let buffer = Buffer.alloc(10); console.log(buffer);

  • Buffer will convert the data to binary and then display it in hexadecimal format

let buffer = Buffer.from(“大家好”); console.log(buffer);

let buffer1 = Buffer.from([0xe5, 0xa4, 0xa7, 0xe5, 0xae, 0xb6, 0xe5, 0xa5, 0xbd]);
这里要注意的是上面的参数要以这种0xe5,  才会转换为字符串
console.log(buffer1); <Buffer e5 a4 a7 e5 ae b6 e5 a5 bd>
console.log(buffer1.toString())大家好
let buffer2 = Buffer.from("大家好");
console.log(buffer2)
/字符串创建
//StringDecoder:   固定名称
let {
    
     StringDecoder } = require("string_decoder");

let decoder = new StringDecoder();

let res1 = decoder.write(buffer1);
let res2 = decoder.write(buffer2);
console.log(res1 + res2);

stream

  • Stream: Stream and data processing are inseparable
//stream   流

const fs = require("fs");
//读取了数据
let rs = fs.createReadStream("11.txt");

//将数据写入
let ws = fs.createReadStream("aa.txt");
//管道
rs.pipe(ws);

console.log(rs);

//流 ,会把数据分成64kb的小文件传输
let num = 0;
let str = "";

//数据传输时,触发的方法
rs.on("data", chunk => {
    
    
        console.log(chunk);
        num++;
        str += chunk;
        console.log(chunk);
        console.log(num)

    })
    //数据传递完成后
rs.on("end", () => {
    
    
    console.log(str)
})

Guess you like

Origin blog.csdn.net/weixin_54645137/article/details/115110938