NodeJS是什么
node.js是一个异步的事件驱动的JavaScript运行时
https://nodejs.org/en/
node.js特性其实是JS的特性:
非阻塞I/O
事件驱动
node历史 — 为性能而生
并发处理
多进程 - C Apache
多线程 - java
异步IO - js
协程 - lua openresty go deno- go TS
与前端的不同
JS核心语法不变
前端 BOM DOM
后端 fs http buffer event os
运行node程序
// 01-run.js
console.log('hello,node.js!');
console.log('run me use: node 01-runnode!');
运行: node 01-runnode.js
每次修改js文件需重新执行才能生效,安装nodemon可以监视文件改动
自动重启: npm i -g nodemon
模块(module)
使用模块(module)
- node内建模块
// 02-useModule.js
// 内建模块直接引入
const os = require('os')
const mem = os.freemem() / os.totalmem() * 100
console.log(`内存占用率${mem.toFixed(2)}%`)
- 第三方模块
https://www.npmjs.com/
// 同级CPU占用率,先安装
npm i download-git-repo -s
// 导入并使用
const download = require('download-git-repo')
download('github:su37josephxia/vue-template', 'test', err => {
console.log(err ? 'Error' : 'Success')
})
导出内容可以是导出对象的属性
// download.js
module.exports.clone = async function()
// 01_run
const {clone} = require('./down')
clone()
核心API
- fs - 文件系统
// 03-fs.js
const fs = require('fs');
// 同步调用
const data = fs.readFileSync('./conf.js'); //代码会阻塞在这里
console.log(data);
// 异步调用
fs.readFile('./conf.js', (err, data) => {
if (err) throw err;
console.log(data);
});
console.log('其他操作');
// fs常常搭配path api使用
const path = require('path')
fs.readFile(path.resolve(path.resolve(__dirname,'./app.js')), (err, data) => {
if (err) throw err;
console.log(data);
});
- Buffer - 用于在 TCP 流、文件系统操作、以及其他上下文中与八位字节流进行交互。 八位字节组成的数
组,可以有效的在JS中存储二进制数据
// 04-buffer.js
// 创建一个长度为10字节以0填充的Buffer
const buf1 = Buffer.alloc(10);
console.log(buf1);
// 创建一个Buffer包含ascii.
// ascii 查询 http://ascii.911cha.com/
const buf2 = Buffer.from('a')
console.log(buf2,buf2.toString())
// 创建Buffer包含UTF-8字节
// UFT-8:一种变长的编码方案,使用 1~6 个字节来存储;
// UFT-32:一种固定长度的编码方案,不管字符编号大小,始终使用 4 个字节来存储;
// UTF-16:介于 UTF-8 和 UTF-32 之间,使用 2 个或者 4 个字节来存储,长度既固定又可变。
const buf3 = Buffer.from('Buffer创建方法');
console.log(buf3);
// 写入Buffer数据
buf1.write('hello');
console.log(buf1);
// 读取Buffer数据
console.log(buf3.toString());
// 合并Buffer
const buf4 = Buffer.concat([buf1, buf3]);
console.log(buf4.toString());
- http:用于创建web服务的模块
const http = require('http');
const server = http.createServer((request, response) => {
console.log('there is a request');
response.end('a response from server');
});
server.listen(3000);