Nodejs 入门学习 (二) Library 的使用

浏览代码时第一行就看不懂了… 隔行如隔山(夸张修辞)
先看代码片段:

const fs = require("fs");
const path = require("path");
const url = require("url");
const config = require('./config.json');
const app = require('express')();
const server = app.listen(config.port);
console.info('Listening port: ' + config.port);

2009年,Node.js 项目诞生,所有模块一律为 CommonJS 格式。
require1 模块通过它加载。我看到这里就没继续看,往下一翻那么长。我就知道这两句就可以了。
那么 fs path url express 就都是library啦,去搜了一下是什么库:
fs nodejs files system2 模块可用于与文件系统进行交互(以类似于标准 POSIX 函数的方式)。
path 就叫路径3,提供了一些实用工具,用于处理文件和目录的路径。
url 就叫URL4,模块用于处理与解析 URL。
express5 是最流行的 Node 框架,是许多其它流行 Node 框架 的底层库。又一次看到这句话 return,后面的目前也不需要看了。
发现还可以读Json文件而且可以直接用,真方便。(吐槽:当年为什么要搞C++,智障遇到了学霸——C++ and NodeJs)。

接着看另一个文件的代码:

exports.create = (config) => 
{
  const server = {};
  ...n
}

exports6 :require 用来加载代码,而 exports 和 module.exports 则用来导出代码。这个文章收录的网站很眼熟,点开主页看了一眼:CNode:Node.js专业中文社区。
查漏补缺,下面操作有点浅拷贝的意思了,不好意思不知道NodeJs有没有指针:

var a = {name: 1};
var b = a;
console.log(a);//1
console.log(b);//1
b.name = 2;
console.log(a);//2
console.log(b);//2
var b = {name: 3};
console.log(a);//2
console.log(b);//3

关于exports的解释:

  1. module.exports 初始值为一个空对象 {}
  2. exports 是指向的 module.exports 的引用
  3. require() 返回的是 module.exports 而不是 exports
    举一反三:exports.create = (config) =>应该就是创建一个导出的library类似的东西吧。config 是参数。

exports.create文档教程没找到,就先这样理解吧。大多数的用法7如下:

module.exports = 
{
    name: 'commonJS_exports.js',
    add: function(a, b)
    {
        return a + b;
    }
}

End~


  1. [阮一峰] require() 源码解读:http://www.ruanyifeng.com/blog/2015/05/require.html. ↩︎

  2. [NodeJs 官网] NodeJs files system:http://nodejs.cn/api/fs.html. ↩︎

  3. [NodeJs 官网] Path:http://nodejs.cn/api/path.html. ↩︎

  4. [NodeJs 官网] URL:http://nodejs.cn/api/url.html. ↩︎

  5. [MDN Web Docs] Express/Node 入门:https://developer.mozilla.org/zh-CN/docs/learn/Server-side/Express_Nodejs/Introduction. ↩︎

  6. [CNode][nswbmw] exports 和 module.exports 的区别:https://cnodejs.org/topic/5231a630101e574521e45ef8. ↩︎

  7. [博客园][谈晓鸣]探索 模块打包 exports和require 与 export和import 的用法和区别:https://www.cnblogs.com/tandaxia/p/12142018.html. ↩︎

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值