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

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

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

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

相关推荐

Excel新函数TEXTSPLIT太强大了,轻松搞定数据拆分!

我是【桃大喵学习记】,欢迎大家关注哟~,每天为你分享职场办公软件使用技巧干货!最近我把WPS软件升级到了版本号:12.1.0.15990的最新版本,最版本已经支持文本拆分函数TEXTSPLIT了,并...

Excel超强数据拆分函数TEXTSPLIT,从入门到精通!

我是【桃大喵学习记】,欢迎大家关注哟~,每天为你分享职场办公软件使用技巧干货!今天跟大家分享的是Excel超强数据拆分函数TEXTSPLIT,带你从入门到精通!TEXTSPLIT函数真是太强大了,轻松...

看完就会用的C++17特性总结(c++11常用新特性)

作者:taoklin,腾讯WXG后台开发一、简单特性1.namespace嵌套C++17使我们可以更加简洁使用命名空间:2.std::variant升级版的C语言Union在C++17之前,通...

plsql字符串分割浅谈(plsql字符集设置)

工作之中遇到的小问题,在此抛出问题,并给出解决方法。一方面是为了给自己留下深刻印象,另一方面给遇到相似问题的同学一个解决思路。如若其中有写的不好或者不对的地方也请不加不吝赐教,集思广益,共同进步。遇到...

javascript如何分割字符串(javascript切割字符串)

javascript如何分割字符串在JavaScript中,您可以使用字符串的`split()`方法来将一个字符串分割成一个数组。`split()`方法接收一个参数,这个参数指定了分割字符串的方式。如...

TextSplit函数的使用方法(入门+进阶+高级共八种用法10个公式)

在Excel和WPS新增的几十个函数中,如果按实用性+功能性排名,textsplit排第二,无函数敢排第一。因为它不仅使用简单,而且解决了以前用超复杂公式才能搞定的难题。今天小编用10个公式,让你彻底...

Python字符串split()方法使用技巧

在Python中,字符串操作可谓是基础且关键的技能,而今天咱们要重点攻克的“堡垒”——split()方法,它能将看似浑然一体的字符串,按照我们的需求进行拆分,极大地便利了数据处理与文本解析工作。基本语...

go语言中字符串常用的系统函数(golang 字符串)

最近由于工作比较忙,视频有段时间没有更新了,在这里跟大家说声抱歉了,我尽快抽些时间整理下视频今天就发一篇关于go语言的基础知识吧!我这我工作中用到的一些常用函数,汇总出来分享给大家,希望对...

无规律文本拆分,这些函数你得会(没有分隔符没规律数据拆分)

今天文章来源于表格学员训练营群内答疑,混合文本拆分。其实拆分不难,只要规则明确就好办。就怕规则不清晰,或者规则太多。那真是,Oh,mygod.如上图所示进行拆分,文字表达实在是有点难,所以小熊变身灵...

Python之文本解析:字符串格式化的逆操作?

引言前面的文章中,提到了关于Python中字符串中的相关操作,更多地涉及到了字符串的格式化,有些地方也称为字符串插值操作,本质上,就是把多个字符串拼接在一起,以固定的格式呈现。关于字符串的操作,其实还...

忘记【分列】吧,TEXTSPLIT拆分文本好用100倍

函数TEXTSPLIT的作用是:按分隔符将字符串拆分为行或列。仅ExcelM365版本可用。基本应用将A2单元格内容按逗号拆分。=TEXTSPLIT(A2,",")第二参数设置为逗号...

Excel365版本新函数TEXTSPLIT,专攻文本拆分

Excel中字符串的处理,拆分和合并是比较常见的需求。合并,当前最好用的函数非TEXTJOIN不可。拆分,Office365于2022年3月更新了一个专业函数:TEXTSPLIT语法参数:【...

站长在线Python精讲使用正则表达式的split()方法分割字符串详解

欢迎你来到站长在线的站长学堂学习Python知识,本文学习的是《在Python中使用正则表达式的split()方法分割字符串详解》。使用正则表达式分割字符串在Python中使用正则表达式的split(...

Java中字符串分割的方法(java字符串切割方法)

技术背景在Java编程中,经常需要对字符串进行分割操作,例如将一个包含多个信息的字符串按照特定的分隔符拆分成多个子字符串。常见的应用场景包括解析CSV文件、处理网络请求参数等。实现步骤1.使用Str...

因为一个函数strtok踩坑,我被老工程师无情嘲笑了

在用C/C++实现字符串切割中,strtok函数经常用到,其主要作用是按照给定的字符集分隔字符串,并返回各子字符串。但是实际上,可不止有strtok(),还有strtok、strtok_s、strto...