// Node中的模块// CommonJS// 模块 -> JS文件// 所有成员私有,只有导出才能用/*** 1. 核心模块: 无须声明直接用* 2. 自定义: 文件* 3. 第三方模块: npm包*/// 1. 核心模块const fs = require('fs');// console.log(fs);const http = require('http');// console.log(http);// 2. 文件模块: 用户自定义,先声明,再导入let site = require('./m1.js');console.log(site);console.log(site.getSite());console.log('-----------------');site = require('./m2.js');console.log(site);console.log(site.getSite());
// * httpconst http = require('http');http.createServer(function (request, response) {// text// response.writeHead(200, { 'Content-Type': 'text/plain' });// response.end('Hello PHP.CN');// html// response.writeHead(200, { 'Content-Type': 'text/html' });// response.end('<h1 style="color:red">PHP.CN</h1>');// jsonresponse.writeHead(200, { 'Content-Type': 'application/json;charset=utf-8' });response.end(`{"id": 3456,"name": "笔记本电脑","price": 10000}`);}).listen(8081, () => {console.log('Server running at http://127.0.0.1:8081/');});
// 文件模块var fs = require('fs');fs.readFile(__dirname + '/file.txt', (err, data) => {if (err) return console.error(err);console.log(data.toString());});// path 模块const str = './node/hello.js';const path = require('path');// 绝对路径console.log(path.resolve(str) + '\n');// 目录console.log(path.dirname(str) + '\n');// 文件名console.log(path.basename(str) + '\n');// 扩展名console.log(path.extname(str) + '\n');const obj = {root: '',dir: './demo',base: 'test.js',ext: '.js',name: 'test',};console.log(path.format(obj));
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号