Node.js
课程链接:http://www.imooc.com/learn/348 (并不是做广告,就是随便找了一个开始的!)
→_→写在前面的废话
long long ago 就像学习前端,然而一直学一点忘一点,从无实践o(╯□╰)o。
终于,大概老天爷看不下去了,到了不得不为了完成任务而开始强制性学习了!突然发现,前端已经无从下手了,react,nodejs,angula,iojs等等等等,啥鬼!
但是,饭要一口口吃,所以从nodejs开始吃了=。=
干巴爹~\(≧▽≦)/~
Chapter 0 环境 + 安装
涉及网址:nodejs.orgAbout里有example
npmjs.com 伸手党福利
安装:git bash
下载 nodejs(官网),安装 (自带npm)
命令行检测安装成功:node -v 和 npm -v
Chapter 1 简易的server:通过回调函数处理req
官网About里的示例代码:
const http = require('http');
const hostname = '127.0.0.1';
const port = 1337;
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello World\n');
}).listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
- 保存成server.js文件;
- 当前文件夹命令行运行 node server.js (起服务,ctrl+c 终止服务)
- 浏览器地址:http://hostname:port (客户端显示hello world)
nodejs本质上是js的一个执行环境(类似chrome的开发者模式,console下有全局变量:window,document等),nodejs全局变量:process等。
Chapter 2 Js模块管理(npm),Commonjs规范
起因:大量js引入导致变量被覆盖、依赖关系出错等
所以,引入命名空间,模块管理
流程:创建模块(a.js)、导出(exports.attr = func1)、加载(var a = require('./a.js'))、使用(a.attr())
exports.attr = func模块实例(若module.exports上有属性,则exports.attr则忽略)
module.exports = func对象类型
个人理解:exports为对外开放的接口
模块——classexports——类的实例(对象),可以调用class的public方法require——import类,返回类的实例