从0到1 koa-node-vue全栈开发(第一章:介绍 node 的基本模块)

293 阅读1分钟

01. http 模块, 该模块可以用于创建服务器

const http = require('http')
// req 表示 客户端传过来的请求
// res 表示 服务端对客户端的响应
const server = http.createServer((req, res) => {
    res.end('hello world')
})
server.listen(3000, '127.0.0.1', () => {
    console.log(`Server running at http://127.0.0.1:3000`)
})

访问127.0.0.1:3000 便可以看到 hello world

02. path 模块, 该模块可以用于文件之间的路径, fs 模块用于读取文件

练习: 读取同目录下的test.txt文件

目录结构

const http = require('http')
const path = require('path')
const fs = require('fs')
const server = http.createServer((req, res) => {
    // 获取到test.txt的文件路径
    const testPath = path.join(__dirname, 'test.txt')
    // 读取文件
    const file = fs.readFileSync(testPath)
    // 设置 状态码
    // 告诉浏览器, 我给你发的数据是什么类型
    // text/plain 纯文本格式
    // charset=utf-8 字符编码
    res.writeHead(200, {
        'Content-Type': 'text/plain;charset=utf-8'
    })
    res.end(file)
})
server.listen(3000, '127.0.0.1', () => {
    console.log(`Server running at http://127.0.0.1:3000`)
})

03. url 模块, 该模块用于解析 url

通过访问不同的url, 返回不同的内容

const http = require('http')
const path = require('path')
const fs = require('fs')
const url = require('url')
const server = http.createServer((req, res) => {
    // 设置 状态码,
    // 告诉浏览器, 我给你发的数据是什么类型
    // text/plain 纯文本格式
    // charset=utf-8 字符编码
    res.writeHead(200, {
        'Content-Type': 'text/plain;charset=utf-8'
    })
    // 返回一个url对象, 会将url的名字和参数进行拆分
    // 例如访问: http://127.0.0.1:3000/home?admin=123456
    // pathname => home
    // query => admin=123456
    const { pathname, query } = url.parse(req.url)
    if (pathname === '/') {
        res.end('hello world')
    } else if (pathname === '/writeFile') {
        // 获取到test.txt的文件路径
        const testPath = path.join(__dirname, 'test.txt')
        // 读取文件
        const file = fs.readFileSync(testPath)
        res.end(file)
    } else {
        res.end(`当前路径为:${pathname}, 参数是: ${query}; 请访问/writeFile`)
    }
})
server.listen(3000, '127.0.0.1', () => {
    console.log(`Server running at http://127.0.0.1:3000`)
})