NodeJs 学习笔记

Node.js 是一个开源的、跨平台的 JavaScript 运行时环境。

官方提供的全局变量:

  • __dirname 当前 JS 文件所在的目录的绝对路径
  • __filename 当前 JS 文件所在的绝对路径

fs 模块

The node:fs module enables interacting with the file system in a way modeled on standand POSIX functions
node:fs 支持以标准POSIX函数为模型化的方式与文件系统交互。

1
2
const fs = require('fs')
fs.readFile('./context.txt',callback)

[Error: ENOENT: no such file or directory, open ‘context.txt’]
path 为相对路径时,./ 指的是 node 运行环境的地址,如在 ‘/‘ 下运行 node ./src/index.js 当前目录是指根目录,/context.txt不存在,所以找不到文件。
具体的 Demo 案例

fs.realpathSync(path[,options])

return the resolved pathname 返回已解析的路径名

  • path <string> | <Buffer> | <URL>
  • options <string> | <Object>
    • encoding <string> Default: ‘utf8’
    • encoding utf8/buffer/base64
  • Returns: <string> | <Buffer>

fs - util

The node:util module supports the needs of Node.js internal APIs. Many of the utilities are useful for application and developers as well.
node:util 模块支持 Node.js 内部 APIs 的需求。许多实用程序对应用程序和模块开发人员是有用的

fs - util.promisify

1
2
3
4
5
/**
* original <Function>
* returns: <Function>
*/
util.promisify(original)

Takes a function following the common error-first callback style, i.e. taking an (err, value) => … callback as the last argument,and returns a version that returns promises.
采用遵循常见的错误优先样式的回调函数,也就是说采用 (err, value) => ... 回调函数作为参数,且返回 promises 版本。

1
2
3
4
// 引入 util 模块
const util = require('util'), fs = require('fs')
let uReadFile = util.promisify(fs.readFile)
uReadFile('./context.txt').then(v => console.log(v.toString()), e => console.log(e))

vm 模块

The node:vm module enables compiling and running code within V8 Virtual Machine context
vm 模块可以在 V8 虚拟机中编译运行代码

1
2
3
4
5
6
vm.runInNewContext(code)
/**
* code <string> 要运行和编译的 JavaScript 代码(The JavaScript code to compile and run)
* contextObject <Object> 一个要被上下文化的对象(An object that will be contextified), 如果未定义,会创建一个新对象(if undefined, a new object will be created.)
* options <Object> | <string>
*/

1
vm.runInNewContext(code, sandbox, "sea-debug.vm")

module

http 模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 1、导入 http 模块
const http = require('http')
// 2、创建 Web 服务
const server = http.createSever()
// 3、绑定 request 事件
server.on('request', (req, res) => {
const url = req.url
let str = '<h1>Not Found</h1>'
if (url === '/' || url === '/index.html') {
str = '<h1>首页</h1>'
} else if (url === '/about.html') {
str = '<h1>关于</h1>'
}

// 处理响应数据乱码的问题
res.setHeader('content-type', 'text/html; charset=utf-8')
// 响应发送给客户端
res.end(str)
})

//4、 启动服务
server.listen(port, host, () => {
console.log(`http://${host}:${port} 已启动`)
})

path 模块

提供用于处理文件路径和目录路径的实用工具

1
const path = require('path')
  • path.resolve()

    将路径或片断序列解析为绝对路径

    1
    2
    3
    4
    5
    6
    // 不传参
    path.resolve() // '/Users/lipingzhang/gitProject/blog'
    path.resolve(1) // TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type number
    path.resolve('a','b') // '/Users/lipingzhang/gitProject/blog/a/b'
    path.resolve('/temp','new') // '/temp/new'
    path.resolve('wwwroot', 'static_files/png/', '../gif/image.gif') // '/Users/lipingzhang/gitProject/blog/wwwroot/static_files/gif/image.gif'
  • path.join()

    使用平台特定分隔符将所有给定 path 片段连接在一起,规范化生成路径

    1
    2
    path.join() // '.' 表示当前目录
    path.join(process.cwd(), 'hexo.json') // '/Users/lipingzhang/Desktop/hexo-cli的副本/a.json'

process

The process object provides information about, and control over(对…的控制),the current Node.js process.
进程对象提供了当前 NodeJs 进程的相关信息和支配。

全局变量,提供有关当前 Node.js 进程信息,并对其进行控制,不需要 require

platform

chdir

process.cwd()

The process.cwd() 返回 ,this method returns the current working directory of the Node.js process.

process.env

The process.env property returns an object containing the user enviroment.

argv

nextTick

Process events

Event: ‘unhandledRejection’

The ‘unhandledRejection’ event is emitted whenever a Promise is rejected and no error handler is attached to the promise within a turn of the event loop.
当 Promise 请求被拒绝且一轮事件循环中没有错误处理程序添加到 promise 时,发送 ‘unhandledRejection’
when programing with Promises, exceptions are encapsulated as ‘rejected promise’
当使用 Promise 编程时,异常被封装为 ‘rejected promise’
Rejections can be caught and handled using promise.catch() and are propagated through a Promise chain.
使用 prmise.catch() 可以捕获并处理 Rejections,通过 promise chain 可以传播 rejections.
The unhandledRejection event is useful for detecting and keeping track of promises that were rejected whose rejections have not yet been handled.
unhandledRejection 事件可以用于检测和跟踪那些未处理或拒绝的 rejections

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
const process = require('node:process')

/**
* reason <Error> | <any> The object with which the promise was rejected (typically an Error object).
* promise <Promise> The rejected promise.
*/
process.on('unhandledRejection', (reason, promise) => {
// ...
})

// The following will also trigger the 'unhandledRejection' event to be emitted:
function SomeResource() {
// Initially set the loaded status to a rejected promise
this.loaded = Promise.reject(new Error('Resource not yet loaded!'));
}

const resource = new SomeResource();

process - 信号事件

Interrupt from keyboard
SIGINT 在终端运行时,可以被所有平台支持,通常可以通过 +C 触发(虽然这个不能配置)。 当终端运行在raw模式,它不会被触发。

1
2
3
process.on('SIGINT', function() {
// callback function
});