Node.js学习——模块,自定义模块

一、http模块、url模块

//引用模块
const http = require('http');
const url = require('url');

// 发送 HTTP 头部 
// HTTP 状态值: 200 : OK 
// 设置 HTTP 头部,状态码是 200,文件类型是 html,字符集是 utf8
http.createServer((req,res)=>{
    res.writeHead(200,{"Content-type": "text/html;charset=utf-8"});  // 解决乱码
    
    console.log(req.url);  
    
    if(req.url !== "/favicon.ico"){

        // url.parse()     解析 URL
        // url.format(urlObject) //是上面 url.parse() 操作的逆向操作 
        // url.resolve(from, to) 添加或者替换地址

        var getValue = url.parse(req.url,true).query;
        console.log(getValue);
        console.log(`姓名: ${getValue.name}, 年龄: ${getValue.age}`);
        res.write(`姓名: ${getValue.name}, 年龄: ${getValue.age}`)
    }
    
    res.end()
    // end 方法使 Web 服务器停止处理脚本并返回当前结果
}).listen(3000)

url.parse()第二个参数加true与不加true的区别

const url = require('url')
let src = 'www.baidu.com?name=zhangsan&age=18'
url.parse(src)
/*
{
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '?name=zhangsan&age=18',
  query: 'name=zhangsan&age=18',
  pathname: 'www.baidu.com',
  path: 'www.baidu.com?name=zhangsan&age=18',
  href: 'www.baidu.com?name=zhangsan&age=18'
}
*/
url.parse(src,true)
/*
{
  protocol: null,
  slashes: null,
  auth: null,
  host: null,
  port: null,
  hostname: null,
  hash: null,
  search: '?name=zhangsan&age=18',
  query: [Object: null prototype] { name: 'zhangsan', age: '18' },
  pathname: 'www.baidu.com',
  path: 'www.baidu.com?name=zhangsan&age=18',
  href: 'www.baidu.com?name=zhangsan&age=18'
}
*/

二、自动重启服务工具

Node.js中的代码修改之后自动重启服务可以使用的工具有:
nodemon, supervisor
安装
nodemon

npm i -g nodemon

supervisor

npm i -g supervisor

使用
supervisor

supervisor index.js

nodemon

nodemon index.js

Node.js中有两类模块,一类是 Node 提供的模块,称为核心模块;另一类是用户编写的模块,称为文件模块。

三、自定义模块

使用require 和exports操作自定义模块
exports导出一个自定义模块时

const obj = {}
module.exports = obj
const  a = function(){}
exports.a = a;

**在使用require时引入一个自定义模块时会根据提供的文件路径获取自定义模块,如果没有写文件路径而是直接写模块的名称则会从node_modules文件夹中查找模块,如果该模块目录中存在index.js文件就可以直接调用,如果该模块中不存在index.js文件则会报错。如何想使用非index.js文件作为入口文件,在该模块目录下 npm init 生成 package.json进行配置 **

const dp = require('dp')

一般的自定义模块的导出分为exports和module.exports

新建exportsMethod.js文件,在里面编写如下代码

const obj = {
    get: function () {
        console.log('这是一个get函数')
    },
    post: function () {
        console.log('这是一个post函数')
    }
}

// exports.xxxx = obj;  

module.exports = obj;

新建一个index.js文件
里面对exportsMethod中的内容进行require

var req = require('./exportsMethod')
console.log(req);

// exports.xxxx = obj;  
// { xxxx: { get: [Function: get], post: [Function: post] } }

// module.exports = obj;
// { get: [Function: get], post: [Function: post] }

四、NPM包管理

  • 常见的npm指令
  • npm init [-y]: 初始化一个package.json文件;
  • npm install 包名: 安装一个包;
  • npm install --save 包名: 将安装的包添加到package.json的依赖中(dependencies);
  • npm install -g 包名: 全局安装一个包;
  • npm docs 包名: 查看包的文档;
  • npm root -g: 查看全局包的安装路径;
  • npm config set prefix "路径": 修改全局包安装路径;
  • npm list: 查看当前目录下安装的所有包;
  • npm list -g: 查看全局包的安装路径下所有的包;
  • npm uninstall 包名: 卸载当前目录下某个包;
  • npm uninstall -g 包名: 卸载全局安装路径下的某个包;
  • npm update 包名: 更新当前目录下的某个包;

初始化一个项目需要使用npm init指令,运行此命令后会自动生成一个package.json文件,该文件中包含一些键值对。

image.png

  • npm安装指定版本的包使用@
npm install node-media-server@2.1.0

package.json文件中的dependencies中的包的版本号的规则如下

^:表示第1、2位版本号不变,最后一位取最新的
~: 表示第1位版本号不变,后面两位取最新的
*:表示所有的版本号取最新的

  • npm、cnpm、yarn的基本指令比较
功能                              NPM                       CNPM                        YARN
初始化某个项目                  npm init                   cnpm init                    yarn init
默认安装依赖操作            npm install/link            cnpm install/link           yarn install/link
    安装某个依赖          npm install taco -s           cnpm install taco -s          yarn add taco
并保存到package.json    
移除某个依赖项目          npm uninstall taco -s         cnpm uninstall taco -s        yarn remove taco
安装某个开发时依赖项目   npm install taco -save-dev    cnpm install taco -save-dev   yarn add taco -dev
更新某个依赖项目           npm update taco -s               cnpm update taco -s       yarn upgrade taco
安装某个全局依赖项目        npm install taco -g           cnpm install taco -g      yarn global add taco
发布/登录/登出           npm publish/login/logout      cnpm publish/login/logout   yarn ublish/login/logout
运行某个命令                npm run/test                    cnpm run/test               yarn run/test
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容