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

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

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

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

相关推荐

selenium(WEB自动化工具)

定义解释Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7,8,9,10,11),MozillaF...

开发利器丨如何使用ELK设计微服务中的日志收集方案?

【摘要】微服务各个组件的相关实践会涉及到工具,本文将会介绍微服务日常开发的一些利器,这些工具帮助我们构建更加健壮的微服务系统,并帮助排查解决微服务系统中的问题与性能瓶颈等。我们将重点介绍微服务架构中...

高并发系统设计:应对每秒数万QPS的架构策略

当面试官问及"如何应对每秒几万QPS(QueriesPerSecond)"时,大概率是想知道你对高并发系统设计的理解有多少。本文将深入探讨从基础设施到应用层面的解决方案。01、理解...

2025 年每个 JavaScript 开发者都应该了解的功能

大家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发。1.Iteratorhelpers开发者...

JavaScript Array 对象

Array对象Array对象用于在变量中存储多个值:varcars=["Saab","Volvo","BMW"];第一个数组元素的索引值为0,第二个索引值为1,以此类推。更多有...

Gemini 2.5编程全球霸榜,谷歌重回AI王座,神秘模型曝光,奥特曼迎战

刚刚,Gemini2.5Pro编程登顶,6美元性价比碾压Claude3.7Sonnet。不仅如此,谷歌还暗藏着更强的编程模型Dragontail,这次是要彻底翻盘了。谷歌,彻底打了一场漂亮的翻...

动力节点最新JavaScript教程(高级篇),深入学习JavaScript

JavaScript是一种运行在浏览器中的解释型编程语言,它的解释器被称为JavaScript引擎,是浏览器的一部分,JavaScript广泛用于浏览器客户端编程,通常JavaScript脚本是通过嵌...

一文看懂Kiro,其 Spec工作流秒杀Cursor,可移植至Claude Code

当Cursor的“即兴编程”开始拖累项目质量,AWS新晋IDEKiro以Spec工作流打出“先规范后编码”的系统工程思维:需求-设计-任务三件套一次生成,文档与代码同步落地,复杂项目不...

「晚安·好梦」努力只能及格,拼命才能优秀

欢迎光临,浏览之前点击上面的音乐放松一下心情吧!喜欢的话给小编一个关注呀!Effortscanonlypass,anddesperatelycanbeexcellent.努力只能及格...

JavaScript 中 some 与 every 方法的区别是什么?

大家好,很高兴又见面了,我是姜茶的编程笔记,我们一起学习前端相关领域技术,共同进步,也欢迎大家关注、点赞、收藏、转发,您的支持是我不断创作的动力在JavaScript中,Array.protot...

10个高效的Python爬虫框架,你用过几个?

小型爬虫需求,requests库+bs4库就能解决;大型爬虫数据,尤其涉及异步抓取、内容管理及后续扩展等功能时,就需要用到爬虫框架了。下面介绍了10个爬虫框架,大家可以学习使用!1.Scrapysc...

12个高效的Python爬虫框架,你用过几个?

实现爬虫技术的编程环境有很多种,Java、Python、C++等都可以用来爬虫。但很多人选择Python来写爬虫,为什么呢?因为Python确实很适合做爬虫,丰富的第三方库十分强大,简单几行代码便可实...

pip3 install pyspider报错问题解决

运行如下命令报错:>>>pip3installpyspider观察上面的报错问题,需要安装pycurl。是到这个网址:http://www.lfd.uci.edu/~gohlke...

PySpider框架的使用

PysiderPysider是一个国人用Python编写的、带有强大的WebUI的网络爬虫系统,它支持多种数据库、任务监控、项目管理、结果查看、URL去重等强大的功能。安装pip3inst...

「机器学习」神经网络的激活函数、并通过python实现激活函数

神经网络的激活函数、并通过python实现whatis激活函数感知机的网络结构如下:左图中,偏置b没有被画出来,如果要表示出b,可以像右图那样做。用数学式来表示感知机:上面这个数学式子可以被改写:...