起因
说来惭愧,谈到node,之前对此了解不多,可能最多使用的就是npm包管理器。在现在这个激烈的竞争环境里要想找到一份好工作感觉确实需要对node有一定掌控,因此这里做个笔记以一个小白视角记录下学习node的过程。
开始
Node: 是一个基于Chrome V8引擎的JavaScript代码运行环境。
-
安装Node
可以node官网下载一个当前版本的node, 官网地址:https://nodejs.org/en/download,根据当前的系统版本选择 windows | mac 其中LTS是稳定版本适合大多数用户,而current是最近的版本功能上较为丰富,我这里选择是稳定版本
安装完成后,可以到本地的终端中查看安装的版本,安装node时会自动安装npm
-
搞一个hello world
在本地创建了一个js文件,helloWorld.js,然后执行 node helloWorld.js 然后就会输出内容了。
-
了解node的一些内置模块
Node.js提供了许多内置模块,包括
fs(文件系统)、http(HTTP协议)、path(路径处理)等。1)
fs(文件系统模块) ,包含了读取(readFile)和写入(writeFile)模块 当然也有// 示例:写入文件内容 const fs = require('fs'); fs.writeFile(__dirname + '/file.txt', 'Hello World', (err) => { if (err) throw err; console.log('文件写入成功'); })// 示例:读取文件内容 const fs = require('fs'); fs.readFile(__dirname + '/file.txt', 'utf8', (err, data) => { if (err) throw err; console.log(data); });2)
path(路径处理模块):Node提供用于处理文件路径的方法。const path = require('path'); // 拼接路径 const joinPath = path.join(__dirname, 'src', 'index.html'); console.log(joinPath); // 获取文件名 const fileName = path.basename('/path/to/file.txt'); console.log(`File Name: ${fileName}`); // 获取文件扩展名 const fileExtension = path.extname('/path/to/file.txt'); console.log(`File Extension: ${fileExtension}`);3)
http模块:创建web服务器的模块const path = require('path'); const fs = require('fs'); const http = require('http'); const serve = http.createServer(); serve.on('request', (req, res) => { const url = req.url; const fileUrl = path.join(__dirname, `../../file/${url}`); res.setHeader('Content-Type', 'text/html; charset=utf-8') fs.readFile(fileUrl, 'utf8', (err, dataStr) => { console.log(err); if (err) res.end(JSON.stringify(err)); res.end(dataStr) }) }); serve.listen(80, () => { console.log('http serve is runing at http://127.0.0.1'); }) -
搞一个自定义模块
// 自定义的工具模块, 这里自定义一个求和的方法,并暴露出去
function add(a, b) {
return a + b
}
module.exports = {
add
}
// 引入自定义模块
const util = reuqire('./util.js');
console.log(util.add(1, 2))
执行后得到如下结果
-
学习Express
express是基于http模块封装的包,需要在项目中安装后使用。安装命令如下
npm install express @4.17.1@符号后可以指定版本,不加的话默认安装最新版本
const express = require('express');
const app = express();
// 中间件
app.use(express.json());
app.post('/user', (req, res) => {
res.send(req.body);
})
app.use(express.urlencoded({extended: false}))
app.post('/book', (req, res) => {
console.log(req.body);
res.send(req.body);
})
app.listen('80', () => {
console.log('express is running at 80 port');
})
这里增加了中间件来处理参数问题。
express能做什么? 1.创建web服务 2.API接口服务 3.获取url动态匹配参数
结语
本次是针对node做一个基础的了解,后面更多的内容还是要深入学习后才能掌握,工作中还是要针对业务方面进行相应的处理。