浏览代码时第一行就看不懂了… 隔行如隔山(夸张修辞)
先看代码片段:
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。express
5 是最流行的 Node 框架,是许多其它流行 Node 框架 的底层库。又一次看到这句话 return,后面的目前也不需要看了。
发现还可以读Json文件而且可以直接用,真方便。(吐槽:当年为什么要搞C++,智障遇到了学霸——C++ and NodeJs)。
接着看另一个文件的代码:
exports.create = (config) =>
{
const server = {};
...n
}
exports
6 :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
的解释:
- module.exports 初始值为一个空对象 {}
- exports 是指向的 module.exports 的引用
- 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~
-
[阮一峰] require() 源码解读:http://www.ruanyifeng.com/blog/2015/05/require.html. ↩︎
-
[NodeJs 官网] NodeJs files system:http://nodejs.cn/api/fs.html. ↩︎
-
[NodeJs 官网] Path:http://nodejs.cn/api/path.html. ↩︎
-
[NodeJs 官网] URL:http://nodejs.cn/api/url.html. ↩︎
-
[MDN Web Docs] Express/Node 入门:https://developer.mozilla.org/zh-CN/docs/learn/Server-side/Express_Nodejs/Introduction. ↩︎
-
[CNode][nswbmw] exports 和 module.exports 的区别:https://cnodejs.org/topic/5231a630101e574521e45ef8. ↩︎
-
[博客园][谈晓鸣]探索 模块打包 exports和require 与 export和import 的用法和区别:https://www.cnblogs.com/tandaxia/p/12142018.html. ↩︎