Node 模块
发布于:2022-01-16 11:11:35
次阅读
Node 模块
- 模块就是一个 js 文件, 内部成员全部私有,只有导出才可以被访问
- 核心模块: 内置,无须声明,直接导入并使用
- 文件模块: 自定义,先声明,再导入
- 第三方模块: npm 安装的
/// 1. 核心模块, 无须声明,直接导入并使用const http = require("http");// console.log(http)const fs = require("fs");// console.log(fs)// 2. 文件模块: 先声明,导出, 再导入;导入必须添加文件路径// exports// 推荐方案,一次性导出module.exports = { domain: "help10086.cn", name: "PHP中文网", getSite() { return this.name + "(**" + this.domain + "**)"; },};// 导入let site = require("./m1.js");// console.log(site)// console.log(site.getSite())site = require("./m2.js");console.log(site);console.log(site.getSite());
Node http 模块
- ndoe-http-server,快速创建 http 服务器
| STT |
api 方法 |
说明 |
| 1 |
response.writeHead |
设置响应头 |
| 2 |
response.end |
写入并结束 |
// http模块// 导入http模块const http = require("http");// 创建一个web服务器// request 请求对象// response 相应对象http .createServer((request, response) => { // 设置响应头 // response.writeHead(200, { "Content-Type": "text/plain" }) // 写入并结束 // response.end("Hello Help") // html // "text/plain" -> "text/html" // response.writeHead(200, { "Content-Type": "text/html" }) // response.end("<h1 style='color:red'>Hello Help</h1>") // json // "text/html" -> "application/json" response.writeHead(200, { "Content-Type": "application/json" }); response.end(` { "msnv":900101, "name": "minh", "email": "minh@gmail.com" } `); }) .listen(8081, () => console.log("http://127.0.0.1:8081/"));
Node fs 模块,文件模块
- ndoe-file-read-async,异步
- ndoe-file-read-sync,同步,服务器端
// 文件模块// console.log(__dirname)const fs = require("fs");fs.readFile(__dirname + "/readme.txt", (err, data) => { if (err) return console.error(err); console.log(data.toString());});
Node path 模块
// path模块const str = "./node/hello.js";const path = require("path");// 绝对路径console.log(path.resolve(str));// 目录部分console.log(path.dirname(str));// 文件名console.log(path.basename(str));// 扩展名console.log(path.extname(str));// pathStr -> objconsole.log(path.parse(str));// obj->pathStrconst obj = { root: "", dir: "./demo", base: "test.js", ext: ".js", name: "test",};console.log(path.format(obj));