关于node.js:Nodejs基础使用PathBufferfs

3次阅读

共计 6382 个字符,预计需要花费 16 分钟才能阅读完成。

Path

const path = require('path')
console.log(__filename)
// 获取门路根底名称, 最初一部分
/**
 * 返回的就是接管门路当中的最初一部分
 * 第二个参数示意扩展名,如果没有设置就返回残缺文件名带后缀
 * 第二个参数作为后缀时,如果没有在以后门路中被匹配到,那么就会疏忽
 * 解决目录门路的时候如果结尾处有门路分隔符,则也会被疏忽掉
 */
console.log(path.basename(__filename))
console.log(path.basename(__filename,'.js')) // 第二个可选参数,匹配后缀,有就显示文件名称,没有就反正残缺文件名
console.log(path.basename(__filename,'.css'))
console.log(path.basename('/a/b/c')) // 返回 path 门路最初一部分

// 获取门路目录名(门路)
/**
 * 返回门路中最初一个局部的上一层目录所在门路
 */
console.log(path.dirname(__filename))
console.log(path.dirname('/a/b/c')) // /a/b 
console.log(path.dirname('/a/b/c/')) // /a/b

// 获取门路扩展名
/**
 * 返回 path 门路中相应文件的后缀名
 * 如果 path 门路当中存在多个点,它匹配的是最初一个点到结尾的内容
 * 
 */
console.log(path.extname(__filename)) // .js
console.log(path.extname('/a/b')) // 空
console.log(path.extname('/a/b/index.html.js.css')) // .css
console.log(path.extname('/a/b/index.html.js.'))  // .

// 解析门路
/**
 * 接管一个门路,返回一个对象,蕴含不同的信息
 * root dir base ext name(最初一部分名称)
 */
const obj = path.parse('a/b/c/index.html')
// {
//     root: '',
//     dir: 'a/b/c',
//     base: 'index.html',
//     ext: '.html',
//     name: 'index'
// }
const obj1 = path.parse('a/b/c/') // {root: '', dir:'a/b', base:'c', ext:'', name: 'c'}
const obj2 = path.parse('a/b/c') // {root: '', dir:'a/b', base:'c', ext:'', name: 'c'}
const obj3 = path.parse('./a/b/c') // {root: '', dir:'./a/b', base:'c', ext:'', name: 'c'}

// 序列化门路
const obj4 = path.parse('./a/b/c')  
console.log(path.format(obj4)) // ./a/b\c

// 判断以后门路是否为绝对路径
console.log(path.isAbsolute('foo')) // false
console.log(path.isAbsolute('/foo')) // true
console.log(path.isAbsolute('///foo')) // true
console.log(path.isAbsolute('')) // false
console.log(path.isAbsolute('.')) // false
console.log(path.isAbsolute('../bar'))  // false

// 拼接门路
console.log(path.join('a/b','c','index.html')) // a\b\c\index.html
console.log(path.join('/a/b','c','index.html')) // \a\b\c\index.html
console.log(path.join('a/b','c','../','index.html')) // a\b\index.html
console.log(path.join('a/b','c','./','index.html')) // a\b\c\index.html
console.log(path.join('a/b','c','','index.html'))  // a\b\c\index.html
console.log(path.join('')) // .  当前工作目录

// 规范化门路
console.log(path.normalize('a/b/c/d')) // a\b\c\d
console.log(path.normalize('a///b/c../d'))  // a\b\c..\d
console.log(path.normalize('a//\\b/c\\/d'))  // a\b\c\d
console.log(path.normalize('a//\b/c\\/d'))  // a\c\d  反斜杠后字母具备非凡意义
console.log(path.normalize('')) // .

// 绝对路径
console.log(path.resolve()) // 打印当前目录
console.log(path.resolve('index.html')) // 打印当前目录 /index.html 最罕用写法
console.log(path.resolve('a','b'))  //  当前目录 \a\b
/**
 * resolve([from],to) 把 to 局部拼接为绝对路径,如果拼接完并不是一个绝对路径,* 那就把当前工作目录加上,让他成为一个绝对路径。from
 */
console.log(path.resolve('/a','b'))  // D:\a\b  这里 '/a' 'b' 成为了 to
console.log(path.resolve('a','/b'))  // D:\b   这里 a 被疏忽,'/b' 成为了 to
console.log(path.resolve('/a','/b'))  // D:\b  这里 '/a' 被疏忽  '/b' 成为了 to

Buffer

Buffer 让 Js 能够操作二进制
全局变量,毋庸 require 的一个全局变量
实现 nodejs 平台下的二进制数据操作
不占据 V8 堆内存大小的内存空间
内存的应用由 Node 管制,由 v8 的 GC 回收
个别配合 Stream 流应用个,充当数据缓冲区

alloc 创立指定字节大小的 buffer
allocUnsafe 创立指定大小的 buffer(不平安)
from 接收数据,创立 buffer

const b1 = Buffer.alloc(10); // 单位是字节
console.log(b1); // <Buffer 00 00 00 00 00 00 00 00 00 00>
const b2 = Buffer.allocUnsafe(10);
console.log(b2); // <Buffer 00 00 00 00 00 00 00 00 00 00>
const b3 = Buffer.from("中");
console.log(b3); // <Buffer e4 b8 ad>  16 进制  utf-8 一个汉字三个字节
const b4 = Buffer.from([1, 2, 3]);
console.log(b4); // <Buffer 01 02 03>
const b5 = Buffer.from([1, 2, "中"]);
console.log(b5); // <Buffer 01 02 00>
const b6 = Buffer.from([0xe4, 0xb8, 0xad]);
console.log(b6, b6.toString()); // <Buffer e4 b8 ad> 中

const a1 = Buffer.alloc(3);
const a2 = Buffer.from(a1); // 空间并非共享
console.log(a1, a2); // <Buffer 00 00 00> <Buffer 00 00 00>
a1[0] = 1;
console.log(a1, a2);  // <Buffer 01 00 00> <Buffer 00 00 00>

fill 应用数据填充 buffer
write 向 buffer 中写入数据
toString 从 buffer 中提取数据
slice 截取 buffer
indexOf 在 buffer 中查找数据
copy 拷贝 buffer 中数据

let buf = Buffer.alloc(6);
buf.fill("123", 1, 3); // 第二个参数是填充开始下标地位, 第三个代表完结地位,这个地位取不到
console.log(buf, buf.toString()); // <Buffer 31 32 33 31 32 33> 123123 , 长度不够就填充,超出就截取

buf.fill(123)
console.log(buf, buf.toString());  // <Buffer 7b 7b 7b 7b 7b 7b> {{{{{{  7b 专 uft- 8 编码是{buf.write("123", 1, 4); // 第二个参数是开始地位,第三个参数为长度
console.log(buf, buf.toString()); // <Buffer 31 32 33 00 00 00> 123


buf = Buffer.from("默认值");
console.log(buf, buf.toString()); // <Buffer e9 bb 98 e8 ae a4 e5 80 bc> 默认值
console.log(buf, buf.toString("utf-8", 3, 9)); // <Buffer e9 bb 98 e8 ae a4 e5 80 bc> 认值 , 第二个参数示意开始下标,第三个示意完结地位


buf = Buffer.from("默认值");
let b1 = buf.slice();  // 第一第二个参数示意开始地位和结束位,顾头不顾尾,如果是正数,示意从尾部开始,- 3 打印进去“值”console.log(b1, b1.toString()); // <Buffer e9 bb 98 e8 ae a4 e5 80 bc> 默认值   --- 从头截取到尾部

buf = Buffer.from("默认值, 阿西洛夫");
console.log(buf, buf.indexOf("阿")); // <Buffer e9 bb 98 e8 ae a4 e5 80 bc 2c e9 98 bf e8 a5 bf e6 b4 9b e5 a4 ab> 10 ---- 中文占三个字节,所以阿字下标是 10
console.log(buf, buf.indexOf("啊", 4)); // <Buffer e9 bb 98 e8 ae a4 e5 80 bc 2c e9 98 bf e8 a5 bf e6 b4 9b e5 a4 ab> -1

let b1 = Buffer.alloc(6);
let b2 = Buffer.from("前端");
b2.copy(b1); // b2 拷贝到 b1 外面
console.log(b1.toString(), b2.toString()); // 前端 前端

let b1 = Buffer.alloc(6);
let b2 = Buffer.from("前端");
b2.copy(b1); // b2 拷贝到 b1 外面 , 第二个参数示意拷贝开始地位,第三个参数从源 buffer 读取开始地位,第四个参数示意源 buffer 读取完结地位,顾头不顾尾
console.log(b1.toString(), b2.toString()); // 前端 前端

let b1 = Buffer.from("前端");
let b2 = Buffer.from("性能");
let b = Buffer.concat([b1, b2]);
console.log(b, b.toString()); // <Buffer e5 89 8d e7 ab af e6 80 a7 e8 83 bd> 前端性能
let b3 = Buffer.concat([b1, b2], 9);
console.log(b3, b3.toString()); // <Buffer e5 89 8d e7 ab af e6 80 a7> 前端性

let b4 = Buffer.alloc(3);
console.log(Buffer.isBuffer(b4));  // true

对 Buffer 实现数组的 split 操作

// buffer 长度创立后是固定的,实现一个 split 办法
ArrayBuffer.prototype.split = function (sep) {let len = Buffer.from(sep).length;
  let result = [];
  let start = 0;
  let offset = 0;

  while ((offset = this.indexOf(sep, start) !== -1)) {result.push(this.slice(start, offset));
    start = offset + len; // 更新 start 地位
  }
  result.push(this.slice(start))
  return result;
};

let buf = "小明喜爱吃馒头,吃水果,吃米饭吃";
let bufArr = buf.split("吃");
console.log(bufArr);  // ['小明喜爱', '馒头,', '水果,', '米饭', '']

FS

Fs 基本操作类
Fs 罕用 API
常见 flag 操作符

r 可读  w 可写  s 同步  + 执行相同操作 x 排它操作 a 追加操作

代码示例

const fs = require("fs");

// readFile
fs.readFile(path.resolve("file.txt"), "utf-8", (err, data) => {console.log(err); // null , 门路谬误就会打印错误信息
  console.log(data); // 123
});

fs.writeFile("data.txt", "hello node.js", (err) => {if (!err) {fs.readFile("data.txt", "utf-8", (err, data) => {console.log(data);  // hello node.js
    });
  }
});

fs.writeFile("data.txt", "hello node.js", (err) => {  // writeFile 笼罩写操作
  if (!err) {fs.readFile("data.txt", "utf-8", (err, data) => {console.log(data);  // hello node.js
    });
  }
});

fs.writeFile("data.txt", "abcd" ,{
    mode:438,
    flag:'r+', // 这个模式不会默认清空文件
    encoding:'utf-8'
}, (err) => {  // writeFile 笼罩写操作
  if (!err) {fs.readFile("data.txt", "utf-8", (err, data) => {console.log(data);  // abcdo node.js
    });
  }
});

// 追加写入
fs.appendFile('data.txt','前端',(err)=>{console.log("write")
})

fs.copyFile('data.txt','dataCopy.txt',(err)=>{console.log("copy success")
})

fs.watchFile('data.txt',{interval:20},(cur,pre)=>{ // 每 20 毫秒监控一次
    if(cur.mtime !== pre.mtime){console.log("file modify") // 批改时会有打印
        fs.unwatchFile('data.txt') // 勾销监控
    }
})
正文完
 0