Node 模块开发,fs,path,nrm,http
Node 是什么
Node 是一个基于 Chrome V8 引擎的 JavaScript 代码运行环境
Node.js 是由ECMAScript 及 Node 环境提供的一些API组成的,包括文件,网络,路径等等一些API
模块化开发规范
- 模块内部可以使用 export 对象进行成员导出,使用 require() 方法导入其他模块
// modul-a.js
const fn = name => `hello ${name}`;
let age = 23;
exports.fn = fn;
exports.age = age;
// 另外一种导出方式 与上面是等价的;但是当他们只想不同的对象的时候,以module.exports为准
module.exports.fn = fn;
module.exports.age = age;
// modul-b.js
const ma = require('./modul-a');
console.log(ma); // { fn: [Function: fn], age: 23 } exports 是一个对象
console.log(ma.fn('zs')) // hello zs
console.log(ma.age); // 23
系统模块
fs 文件操作
const fs = require('fs');
读取文件内容
fs.readFile(文件路径包含文件名, [文件编码], callback);
fs.readFile('./Node/modul-a.js', 'utf8', (err, doc) => {
console.log(err)
if (err == null) {
console.log(doc);
}
})
文件写入内容
fs.writeFile(文件路径包含文件名, 内容, callback);
let content = 'let name = "zs";';
// 如果文件不存在 系统会重新创建; 写入的内容为重新写入
fs.writeFile('./Node/write.js', content, err => {
if (err == null) {
return
}
console.log('文件写入成功');
})
path 路径操作
const path = require('path');
console.log(__dirname); // 当前文件的绝对路径
路径拼接
path.join('path1', 'path2', ...);
let finalPath = path.join('public', 'uploads', 'images'); // public\uploads\images
第三方模块
nrm:npm下载地址切换工具
npm install nrm -g
nrm ls 查询可用的下载地址一般使用淘宝
nrm use taobao 切换下载地址
http 模块
const http = require('http')
const url = require('url') // 获取 url 中 get参数 需要借助 url 模块
const app = http.createServer() // 服务器对象
app.on('request', (req, res) => {
console.log(req.headers) // 返回一个对象,记录了请求头信息
console.log(req.url) // 获取浏览器url请求路径 默认是 /
console.log(req.method) // 获取客户端的请求方式
// url.parse() 返回一个新对象 如果第二个参数为 true 会把 query键的值由字符串更改为对象 pathname 等价于原来没有参数时候的 req.url
let {pathname, query} = url.parse(req.url)
console.log(query.name) // 获取get指定参数
// 返回客户端响应头,状态码 第二个参数必须是一个对象
res.writeHeader(200, {
'content-type': 'text/html;'
})
res.end('<h3>hello world</h3>') // 响应内容
})
app.listen(3000) // 监听 3000 端口
处理 post 请求参数
获取post参数需要使用data和end事件;使用querystring系统模块将参数转换为对象格式
const http = require('http')
const querystring = require('querystring')
const app = http.createServer()
app.on('request', (req, res) => {
let postData = ''
req.on('data', (chunk) => postData += chunk)
// postData 此时和 get 获取来的参数一样是一个字符串需要转换
req.on('end', () => {
let format = querystring.parse(postData)
})
res.end('ok')
})
app.listen(3000)