Practical Node.js摘录(2018版)第1,2章。
视频:https://node.university/courses/short-lectures/lectures/3949510
另一本书:全栈JavaScript,学习backbone.js node.js and MongoDB.
1,2章:
- Setting up Node.js and Other Essentials [2nd Edition]
- Using Express.js 4 to Create Node.js Web Apps [2nd Edition]
第一章
- Node.js and npm (Node package manager) installation
- Node.js script launches
- Node.js syntax and basics
- Node.js integrated development environments (IDEs) and code editors
- Awareness of file changes
- Node.js program debugging
Key Differences Between Node and Browser JavaScript
node没有window, 因此也就没有document对象模型,没有DOM,没有hierarchy of element。
node有global object.(小写字母),可以在任何node环境,文件,app中使用。
你可以在global object上创建property,同时它也有内建的properties。这些properties也是global的,因此可以用在anywhere。
在browser,有内建的modules。
但是node没有core modules,通过文件系统可以使用各种modules。
REPL
进入node控制台,直接在terminal输入node, 这是一个virtual 环境,通常称为read-eval-print-loop
可以直接执行Node.js/JavaScript代码。
⚠️:
require()方法,是node.js的modules功能,在chrome browser 控制台上会报告❌ReferenceError。
Launching Node.js Scripts
语法:
node filename node -e "直接输入javaScript代码"
//如$ node -e "console.log(new Date())
参数e, 是evaluate script, -e, --eval=...
Node.js Basics and Syntax
Node.js使用chrome v8引擎和ESCAScript,因此大多数语法和前端js类似。
- Loose typing
- Buffer—Node.js super data type
- Object literal notation
- Functions
- Arrays
- Prototypal nature
- Conventions
Loose Typing
大多数时候支持自动typecasing。primitives包括:String, Number, Boolean, Undefined, Null。
Everything else is an object。包括:Class, Function, Array, RegExp。
在Js,String, Number, Boolean对象有帮助方法:
//例子:
'a' === new String('a') //false, 因为使用new String会返回对象
//所以用toString()
'a' === new String('a').toString() // true
//或者使用==,执行自动typecasing, ===加入了类型判断
Buffer—Node.js Super Data Type
Buffer是Node.js增加的数据类型。
它是一个有效的数据存储data store.
它功能上类似Js的ArrayBuffer。
⚠️:(具体内容,如何创建,使用未看。)
Object Literal Notation对象字面量符号
Node8以后的版本都支持ES6。
比如,箭头函数,使用class, 可以extend另一个对象{...anotherObject}, 动态定义属性名,使用super()关键字,使用函数的短语法。
Functions
在Node.js,函数最重要,它们是对象!可以有属性。
使用function expression定义一个函数,可以anonymous。例子:
//outer 'this'
const f = () => {
//still outer "this"
console.log('Hi')
return true
}
JavaScript把函数当成对象,所以函数也可以作为参数传递给另一个函数,嵌套函数会发生callbacks。
Arrays
let arr4 = new Array(1,"Hi", {a:2}, () => {console.log('boo')})
arr4[3]() // boo
从Array.prototype,global object继承了一些方法。
Prototypal Nature
JavaScript没有classes的概念,对象都是直接继承自其他对象,即prototypal inheritance!
在JS有几种继承模式的类型:
- Classical
- Pseudoclassical
- Functional
ES6,引用了class,但本质未变,只是写法上更方便。使用了new , class, extends关键字。
具体见之前博客:https://www.cnblogs.com/chentianwei/p/10197813.html
传统的是函数继承模式:
//函数user
let user = function(ops) {
return {
firstName: ops.firstName || 'John',
lastName: ops.lastName || 'Doe',
email: ops.email || 'test@test.com',
name: function() { return this.firstName + this.lastName}
}
} //继承函数user,
let agency = function(ops) {
ops = ops || {}
var agency = user(ops)
agency.customers = ops.customers || 0
agency.isAegncy = true
return agency
}
Node.js Globals and Reserved Keywords
- process
- global
- module.exports, exports
Node.js Process Information
每个Node.js script的运行,都是一个系统进程。
可以使用process对象得到,当前进程的相关信息:
process.pid process.cwd() node -e "console.log(process.pid)"
global Scope in Node.js
浏览器中的window, document对象都不存在于Node.js.
global是全局对象,可以使用大量方法。如console, setTimeout(), global.process, global.require(), global.module
例子: global.module
Module {
id: '<repl>',
exports: {},
parent: undefined,
filename: null,
loaded: false,
children: [],
paths:
[ '/Users/chentianwei/repl/node_modules',
'/Users/chentianwei/node_modules',
'/Users/node_modules',
'/node_modules',
'/Users/chentianwei/.node_modules',
'/Users/chentianwei/.node_libraries',
'/Users/chentianwei/.nvm/versions/node/v11.0.0/lib/node' ] }
process对象有一系列的有用的信息和方法:
//退出当前进程,如果是在node环境编辑器,直接退出回到终端目录:
process.exit() ⚠️在node环境,直接输入process,得到process对象的所有方法和信息。
Exporting and Importing Modules
module.exports = (app) => {
//
return app
}
const messages = require('./routes/messages.js')
真实案例使用:
const messages = require(path.join(__dirname, 'routes', 'messages.js'))
解释:
_dirname获得绝对路径, 在加上routes/message.js,得到真实的路径。
Node.js Core Modules
核心/基本模块
Node.js不是一个沉重的标准库。核心模块很小,但足够建立任何网络应用。
Networking is at the core of Node.js!
主要但不是全部的core modules, classes, methods, and events include the following:
http
(http://nodejs.org/api/http.html#http_http): Allows to create HTTP clients and serversutil
(http://nodejs.org/api/util.html): Has a set of utilitiesquerystring
(http://nodejs.org/api/querystring.html): Parses query-string formatted dataurl
(http://nodejs.org/api/url.html): Parses URL datafs
(http://nodejs.org/api/fs.html): Works with a file system (write, read)
方便的Node.js Utilities
- Crypto (http://nodejs.org/api/crypto.html): Has randomizer, MD5, HMAC-SHA1, and other algorithms
- Path (http://nodejs.org/api/path.html): Handles system paths
- String decoder (http://nodejs.org/api/string_decoder.html): Decodes to and from
Buffer
andString
types
使用npm安装Node.js的Modules
留意我们需要package.json, node_modules文件夹来在本地安装modules:
$ npm install <name>
例子:
npm install superagent //然后在program.js,引进这个模块。
const superagent = require('superagent')
使用npm的一大优势,所有依赖都是本地的。
比如:
module A 使用modules B v1.3,
module C 使用modules B v2.0
A,C有它们各自的B的版本的本地拷贝。
这种策略比Ruby和其他一些默认使用全局安装的平台更好。
最好不要把node_modules文件夹放入Git repository,当这个程序是一个模块会被其他app使用的话。
当然,推荐把node_modules放入会部署的app中,这样可以防备由于依赖更新导致的意外损害。
Taming Callbacks in Node.js
callbacks让node.js异步。使用promise, event emitters,或者async library可以防止callback hell
Hello World Server with HTTP Node.js Module
Node.js主要用于建立networking app包括web apps。
因为天然的异步和内建的模块(net, http),Node.js在networks方面快速发展。
下面是一个例子:
创建一个server object, 定义请求handler, 传递数据回到recipient,然后开启server.js。
const http = require('http')
const port = 3000
const server = http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end('Hello World\n')
}).listen(port, () => {
console.log(`Server running at http://localhost:${port}`)
})
首先,需要用http module。并设置服务port.
然后,创建一个server, 它有一个回调函数,函数包括response的处理代码。
为了设置right header和status code:
res.writeHead(200, {'Content-Type': 'text/plain'})
再输出一个字符串,使用end symbol.
req和res参数是关于一个HTTP request和response data的信息。另外这2个参数可以使用stream(这是一个模块)
再然后,为了让server接受请求requests,使用listen()方法
最后,再terminal输入:
node server.js
terminals上显示console.log的信息:
Server running at http://localhost:3000
//在浏览器打开连接,可看到'Hello World'字样。这是res.end()实现的。
Debugging Node.js Programs
现代软件开发者,可以使用如Chrome Developer Tools, Firfox Firebug。
因为Node.js和浏览器 JavaScript环境类似,所以我们可以使用大量丰富的Debug工具:
- Core Node.js Debugge(非用于交互界面)
- Node Inspector: Port of Google Chrome Developer Tools ✅推荐✅。
- IDEs: WebStorm, VS Code and other IDEs
Core Node.js Debugger
最好的debugger是 console.log(),
Practical Node.js摘录(2018版)第1,2章。的更多相关文章
- Practical Node.js (2018版) 第7章:Boosting Node.js and Mongoose
参考:博客 https://www.cnblogs.com/chentianwei/p/10268346.html 参考: mongoose官网(https://mongoosejs.com/docs ...
- 自制node.js + npm绿色版
自制node.js + npm绿色版 Node.js官网有各平台的安装包下载,不想折腾的可以直接下载安装,下面说下windows平台下如何制作绿色版node,以方便迁移. 获取node.exe下载 ...
- node.js在2018年能继续火起来吗?我们来看看node.js的待遇情况
你知道node.js是怎么火起来的吗?你知道node.js现在的平均工资是多少吗?你知道node.js在2018年还能继续火吗?都不知道?那就来看文章吧,多学点node.js,说不定以后的你工资就会高 ...
- Practical Node.js (2018版) 第5章:数据库 使用MongoDB和Mongoose,或者node.js的native驱动。
Persistence with MongoDB and Mongoose https://github.com/azat-co/practicalnode/blob/master/chapter5/ ...
- Practical Node.js (2018版) 第10章:Getting Node.js Apps Production Ready
Getting Node.js Apps Production Ready 部署程序需要知道的方面: Environment variables Express.js in production So ...
- Practical Node.js (2018版) 第9章: 使用WebSocket建立实时程序,原生的WebSocket使用介绍,Socket.IO的基本使用介绍。
Real-Time Apps with WebSocket, Socket.IO, and DerbyJS 实时程序的使用变得越来越广泛,如传统的交易,游戏,社交,开发工具DevOps tools, ...
- Practical Node.js (2018版) 第8章:Building Node.js REST API Servers
Building Node.js REST API Servers with Express.js and Hapi Modern-day web developers use an architec ...
- Practical Node.js (2018版) 第3章:测试/Mocha.js, Chai.js, Expect.js
TDD and BDD for Node.js with Mocha TDD测试驱动开发.自动测试代码. BDD: behavior-driven development行为驱动开发,基于TDD.一种 ...
- 《Node.js 高级编程》简介与第二章笔记
<Node.js 高级编程> 作者简介 Pedro Teixerra 高产,开源项目程序员 Node 社区活跃成员,Node公司的创始人之一. 10岁开始编程,Visual Basic.C ...
随机推荐
- Received empty response from Zabbix Agent at [172.16.1.7]...
Centos7.5 zabbix添加主机发现ZBX爆红报错 原因:在配置/etc/zabbix/zabbix_agentd.conf中172.16.1.71写成了127.16.1.71 解决方法:重 ...
- smbclient和mount -t cifs共享win的共享文件夹? autocad小记
插入U盘没有反应? 首先,打开设备管理器, 发现usb大容量设备为黄色感叹号 其次, 将这个usb大容量设备先卸载, 然后点击"自动扫描硬件变化",就可以重新自动安装usb的驱动. ...
- 【问题解决:连接异常】 java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
问题描述: MySQL更新到8.0.11之后连接数据库时会报出错误 Your login attempt was not successful, try again.Reason: Could not ...
- P4568 [JLOI2011]飞行路线
思路 套路题 建出k+1分层图,从上一层走到下一层代表坐了一次免费航线,跑最短路即可 注意可能有情况不需要耗完所有k次机会,所以应从每层的终点向下一层终点连一条边权为0的边 代码 #include & ...
- P2051 [AHOI2009]中国象棋(动态规划)
思路 好像是一道挺水的计数的,不知道为什么会是紫题 显然每行和每列最多放两个 首先考虑状压,然后发现三进制状压可做,但是三进制太麻烦了,可以拆成两个二进制,一个表示该列是否是放了一个的,一个表示该列是 ...
- --HTML标签1
文字标签: <h>标签 标题,分为<h1>-<h6>(6级) <b> 加粗 <u> 下滑线 <s>或<strike> ...
- HDU 3401 Trade(斜率优化dp)
http://acm.hdu.edu.cn/showproblem.php?pid=3401 题意:有一个股市,现在有T天让你炒股,在第i天,买进股票的价格为APi,卖出股票的价格为BPi,同时最多买 ...
- Shell 脚本批量创建数据库表
使用 Shell 脚本批量创建数据表 系统:Centos6.5 64位 MySQL版本:5.1.73 比如下面这个脚本: #!/bin/bash #批量新建数据表 for y in {0..199}; ...
- android studio 的基本使用和建立一个小项目
https://github.com/allenxieyusheng/Android-Studio
- 前端性能优化之按需加载(React-router+webpack)
一.什么是按需加载 和异步加载script的目的一样(异步加载script的方法),按需加载/代码切割也可以解决首屏加载的速度. 什么时候需要按需加载 如果是大文件,使用按需加载就十分合适.比如一个近 ...