Node

Node

Node.js® is an open-source, cross-platform JavaScript runtime environment, is a JavaScript runtime built on the V8 JavaScript engine.

Node中无法使用DOM和BOM等浏览器内置API

学习的官网文档链接:https://nodejs.org/docs/latest-v17.x/api/documentation.html

fs

fs.readFile

1
2
3
4
5
6
//用module导入的方式
import { readFile } from 'fs'
readFile('./example/ex1.json', (err, data) => {
console.log(data)
})
//报错: Cannot use import statement outside a module, To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
1
2
3
4
5
6
7
const fs = require("fs")
fs.readFile("./example/ex1.json", (err, data) => {
console.log(data)
})

//<Buffer 7b 0d 0a 20 20 20 20 22 6e 75 6d 31 22 3a 20 31 0d 0a 7d>
//If no encoding is specified, then the raw buffer is returned.
1
2
3
4
5
6
7
const fs = require("fs")
fs.readFile("./example/ex1.json", "utf8", (err, data) => {
console.log(data)
})
//{
// "num1": 1
//}

可以判断err对象是否为null,从而知晓文件读取的是否成功

fs.writeFile

1
2
3
4
fs.writeFile("./example/ex1.json", "123",'utf8', (err) => {
console.log(err) //成功则是null
})
//文件内容被覆盖了

example

使用fs,将源文件的数据整理放到另一个文件中

源文件:

1
小红=99 小白=100 小黄=80 小1=100

目标内容:

1
2
3
4
小红:99
小白:100
小黄:80
小1:100

实现:

1
2
3
4
5
6
7
8
const fs = require("fs")
fs.readFile("./example/grade.txt", "utf8", (err, data) => {
let tem1 = data.replace(/\=/g, ":") //全匹配
let tem2 = tem1.replace(/\ /g, "\n")
fs.writeFile("./example/grade-1.txt", tem2, (err) => {
console.log(err)
})
})

Node
http://example.com/2023/02/23/Node/
作者
John Doe
发布于
2023年2月23日
许可协议