百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

NodeJS,http模块、url模块案例,CommonJS模块规范,模块化

itomcoil 2024-12-19 13:43 22 浏览

NodeJS http模块

http模块

主要用于创建http server服务,并且:支持更多特性;不缓冲请求和响应;处理流相关。

url模块

用于解析URL中的参数,提供了三个方法,分别是url.parse(); url.format(); url.resolve()。

案例1:

var http = require('http');
// request --> 请求信息
// response --> 响应信息
http.createServer(function (request, response) {
  // 设置响应头   
  response.writeHead(200, {'Content-Type': 'text/plain'});
  // 輸出內容
  response.end('Hello World');
}).listen(3000);
console.log("http server port:",3000);

案例2:

const http = require('http');
const url = require('url');

http.createServer((req,res)=>{
  console.log("请求地址:",req.url);
  if(req.url!='/favicon.ico'){
    // URL模块解析
    var urlObj = url.parse(req.url,true);
    console.log("urlObj",urlObj);
    var getValue = urlObj.query;
    console.log("获取get请求参数:",getValue);
    // http://127.0.0.1:3000/get?id=1234&name=%E6%9D%8E%E5%9B%9B
    console.log("getValue.id",getValue.id);
    console.log("getValue.name",getValue.name);
    // 设置响应头
    res.writeHead(200,{'Content-Type':'text/html;charset="UTF-8"'});
    // 响应内容
    res.write("<head><mate charset='utf-8'/></head>");
    res.write("<h1>你好,node js、GET请求~</h1>");
    // 结束响应
    res.end();
  }
}).listen(3000);

CommonJS模块规范及模块化

NodeJS模块分类

Node.js中根据模块来源的不同,将模块分为3大类:

1、内置模块(内置模块是由 Node.js 官方提供的,例如 fs、path、http 等)。

2、自定义模块(用户创建的每个 .js 文件,都是自定义模块)。

3、第三方模块(由第三方开发出来的模块,并非官方提供的内置模块,也不是用户创建的自定义模块,使用前需要先下载)。

模块化

CommonJS

CommonJS是一种模块规范,最初被应用于Nodejs,成为Nodejs的模块规范。

CommonJS中,一个文件就是一个模块,定义一个模块导出通过exports或者module.exports挂载即可。CommonJS加载模块时,使用require,使用exports来做模块输出,还有module,__filename, __dirname这些变量。

模块化案例

var http = require('http');
// 从JS中引入
var dateTools = require('./module/dateTools.js');
var requestApi = require('./module/requestApi.js');
var requestApi2 = require('./module/requestApi2.js');
var requestApi3 = require('./module/requestApi3.js');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  // exports.dateFormat
  var date = new Date();
  console.log("dateTools", dateTools);
  response.write(dateTools.dateFormat("YYYY-mm-dd HH:MM:SS",date));
  console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  // exports.myRequest = request;
  // requestApi { myRequest: { get: [Function: get], post: [Function: post] } }
  console.log("requestApi", requestApi);
  requestApi.myRequest.get();
  console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  // module.exports = request;
  // requestApi2 { get: [Function: get], post: [Function: post] }
  console.log("requestApi2", requestApi2);
  requestApi2.get();
  requestApi2.post();
  console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  // requestApi3 { get: [Function (anonymous)], post: [Function (anonymous)] }
  console.log("requestApi3", requestApi3);
  requestApi3.get();
  requestApi3.post();
  response.end();
}).listen(3000);

console.log('Server running at http://127.0.0.1:3000/');

module/dateTools.js

function dateFormat(fmt, date) {
  let ret;
  const opt = {
      "Y+": date.getFullYear().toString(),        // 年
      "m+": (date.getMonth() + 1).toString(),     // 月
      "d+": date.getDate().toString(),            // 日
      "H+": date.getHours().toString(),           // 时
      "M+": date.getMinutes().toString(),         // 分
      "S+": date.getSeconds().toString()          // 秒
      // 有其他格式化字符需求可以继续添加,必须转化成字符串
  };
  for (let k in opt) {
    ret = new RegExp("(" + k + ")").exec(fmt);
    if (ret) {
      fmt = fmt.replace(ret[1], (ret[1].length == 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, "0")))
    };
  };
  return fmt;
}

exports.dateFormat = dateFormat;

module/requestApi.js

var request={
  get:function(){
    console.log("get()......");
  },
  post:function(){
    console.log("post()......");
  }
}

exports.myRequest = request;

module/requestApi2.js

var request={
  get:function(){
    console.log("get()......");
  },
  post:function(){
    console.log("post()......");
  }
}

module.exports = request;

module/requestApi3.js

exports.get = function(){
  console.log("get()......");
};
exports.post = function(){
  console.log("post()......");
};

NodeJS模块化

node-modules

node_modules是安装node后用来存放用包管理工具下载安装的包的文件夹/目录,模块化默认的文件夹/目录名称为:node_modules。

案例:

// 直接写node_modules下的名称,默认加载index.js
const demo01 = require("demo01");
// 直接写node_modules下的名称,没有index.js,npm init --yes生成package.json
const demo02 = require("demo02");

demo01.get();
demo01.post();

demo02.get();
demo02.post();

demo01\index.js

exports.get = function(){
  console.log("get()......");
};
exports.post = function(){
  console.log("post()......");
};

demo02\demo02.js

exports.get = function(){
  console.log("get()......");
};
exports.post = function(){
  console.log("post()......");
};

demo02/package.json

{
  "name": "demo02",
  "version": "1.0.0",
  "description": "",
  "main": "demo02.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

package.json文件:定义模块(NodeJS中的包)的配置信息,定义:名称、版本、许可证等元数据。package.json文件可以手工编写,也可以使用npm init命令自动生成。

生成命令:npm init --yes

相关推荐

Python Qt GUI设计:将UI文件转换Python文件三种妙招(基础篇—2)

在开始本文之前提醒各位朋友,Python记得安装PyQt5库文件,Python语言功能很强,但是Python自带的GUI开发库Tkinter功能很弱,难以开发出专业的GUI。好在Python语言的开放...

Connect 2.0来了,还有Nuke和Maya新集成

ftrackConnect2.0现在可以下载了--重新设计的桌面应用程序,使用户能够将ftrackStudio与创意应用程序集成,发布资产等。这个新版本的发布中还有两个Nuke和Maya新集成,...

Magicgui:不会GUI编程也能轻松构建Python GUI应用

什么是MagicguiMagicgui是一个Python库,它允许开发者仅凭简单的类型注解就能快速构建图形用户界面(GUI)应用程序。这个库基于Napari项目,利用了Python的强大类型系统,使得...

Python入坑系列:桌面GUI开发之Pyside6

阅读本章之后,你可以掌握这些内容:Pyside6的SignalsandSlots、Envents的作用,如何使用?PySide6的Window、DialogsandAlerts、Widgets...

Python入坑系列-一起认识Pyside6 designer可拖拽桌面GUI

通过本文章,你可以了解一下内容:如何安装和使用Pyside6designerdesigner有哪些的特性通过designer如何转成python代码以前以为Pyside6designer需要在下载...

pyside2的基础界面(pyside2显示图片)

今天我们来学习pyside2的基础界面没有安装过pyside2的小伙伴可以看主页代码效果...

Python GUI开发:打包PySide2应用(python 打包pyc)

之前的文章我们介绍了怎么使用PySide2来开发一个简单PythonGUI应用。这次我们来将上次完成的代码打包。我们使用pyinstaller。注意,pyinstaller默认会将所有安装的pack...

使用PySide2做窗体,到底是怎么个事?看这个能不能搞懂

PySide2是Qt框架的Python绑定,允许你使用Python创建功能强大的跨平台GUI应用程序。PySide2的基本使用方法:安装PySide2pipinstallPy...

pycharm中conda解释器无法配置(pycharm安装的解释器不能用)

之前用的好好的pycharm正常配置解释器突然不能用了?可以显示有这个环境然后确认后可以conda正在配置解释器,但是进度条结束后还是不成功!!试过了pycharm重启,pycharm重装,anaco...

Conda使用指南:从基础操作到Llama-Factory大模型微调环境搭建

Conda虚拟环境在Linux下的全面使用指南:从基础操作到Llama-Factory大模型微调环境搭建在当今的AI开发与数据分析领域,conda虚拟环境已成为Linux系统下管理项目依赖的标配工具。...

Python操作系统资源管理与监控(python调用资源管理器)

在现代计算环境中,对操作系统资源的有效管理和监控是确保应用程序性能和系统稳定性的关键。Python凭借其丰富的标准库和第三方扩展,提供了强大的工具来实现这一目标。本文将探讨Python在操作系统资源管...

本地部署开源版Manus+DeepSeek创建自己的AI智能体

1、下载安装Anaconda,设置conda环境变量,并使用conda创建python3.12虚拟环境。2、从OpenManus仓库下载代码,并安装需要的依赖。3、使用Ollama加载本地DeepSe...

一文教会你,搭建AI模型训练与微调环境,包学会的!

一、硬件要求显卡配置:需要Nvidia显卡,至少配备8G显存,且专用显存与共享显存之和需大于20G。二、环境搭建步骤1.设置文件存储路径非系统盘存储:建议将非安装版的环境文件均存放在非系统盘(如E盘...

使用scikit-learn为PyTorch 模型进行超参数网格搜索

scikit-learn是Python中最好的机器学习库,而PyTorch又为我们构建模型提供了方便的操作,能否将它们的优点整合起来呢?在本文中,我们将介绍如何使用scikit-learn中的网格搜...

如何Keras自动编码器给极端罕见事件分类

全文共7940字,预计学习时长30分钟或更长本文将以一家造纸厂的生产为例,介绍如何使用自动编码器构建罕见事件分类器。现实生活中罕见事件的数据集:背景1.什么是极端罕见事件?在罕见事件问题中,数据集是...