大神的node书,免费

视频:https://node.university/courses/short-lectures/lectures/3949510

另一本书:全栈JavaScript,学习backbone.js node.js and MongoDB.

1,2章:

  1. Setting up Node.js and Other Essentials [2nd Edition]
  2. 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有几种继承模式的类型:

  1. Classical
  2. Pseudoclassical
  3. 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:

方便的Node.js Utilities


使用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章。的更多相关文章

  1. Practical Node.js (2018版) 第7章:Boosting Node.js and Mongoose

    参考:博客 https://www.cnblogs.com/chentianwei/p/10268346.html 参考: mongoose官网(https://mongoosejs.com/docs ...

  2. 自制node.js + npm绿色版

    自制node.js + npm绿色版   Node.js官网有各平台的安装包下载,不想折腾的可以直接下载安装,下面说下windows平台下如何制作绿色版node,以方便迁移. 获取node.exe下载 ...

  3. node.js在2018年能继续火起来吗?我们来看看node.js的待遇情况

    你知道node.js是怎么火起来的吗?你知道node.js现在的平均工资是多少吗?你知道node.js在2018年还能继续火吗?都不知道?那就来看文章吧,多学点node.js,说不定以后的你工资就会高 ...

  4. Practical Node.js (2018版) 第5章:数据库 使用MongoDB和Mongoose,或者node.js的native驱动。

    Persistence with MongoDB and Mongoose https://github.com/azat-co/practicalnode/blob/master/chapter5/ ...

  5. Practical Node.js (2018版) 第10章:Getting Node.js Apps Production Ready

    Getting Node.js Apps Production Ready 部署程序需要知道的方面: Environment variables Express.js in production So ...

  6. Practical Node.js (2018版) 第9章: 使用WebSocket建立实时程序,原生的WebSocket使用介绍,Socket.IO的基本使用介绍。

    Real-Time Apps with WebSocket, Socket.IO, and DerbyJS 实时程序的使用变得越来越广泛,如传统的交易,游戏,社交,开发工具DevOps tools, ...

  7. 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 ...

  8. 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.一种 ...

  9. 《Node.js 高级编程》简介与第二章笔记

    <Node.js 高级编程> 作者简介 Pedro Teixerra 高产,开源项目程序员 Node 社区活跃成员,Node公司的创始人之一. 10岁开始编程,Visual Basic.C ...

随机推荐

  1. Java——List:list.add(index, element)和list.set(index, element)的区别

    add(index, element) 含义:在集合索引为index的位置上增加一个元素element,集合list改变后list.size()会增加1 用法 testList.add(index, ...

  2. Bootstrap3基础 btn-xs/sm... 按钮的四种大小

      内容 参数   OS   Windows 10 x64   browser   Firefox 65.0.2   framework     Bootstrap 3.3.7   editor    ...

  3. 多线程编程:一个指令重排序引发的chaos

    先贴出正确的代码: package com.xiaobai.thread.main; import lombok.extern.slf4j.Slf4j; @Slf4j public class Thr ...

  4. hihoCoder week6 01背包

    01背包 题目链接 https://hihocoder.com/contest/hiho6/problem/1 #include <bits/stdc++.h> using namespa ...

  5. 网络_TCP连接的建立与释放

    三报文握手 1.概述 TCP是面向连接的协议.TCP建立连接的过程叫做握手,握手需要在客户和服务器之间交换三个TCP报文段,即我们说的"三次握手"(严格讲是一次握手过程中交换了三个 ...

  6. 题解——POJ 2234 Matches Game

    这道题也是一个博弈论 根据一个性质 对于\( Nim \)游戏,即双方可以任取石子的游戏,\( SG(x) = x \) 所以直接读入后异或起来输出就好了 代码 #include <cstdio ...

  7. 洛谷P1803 凌乱的yyy dp

    我要日更嘤嘤嘤>_< 原题戳>>https://www.luogu.org/problem/show?pid=1803<<(其实是戳不动的,复制粘贴吧) 题目背景 ...

  8. demoshow - webdemo展示助手

    demoshow - web demo展示助手 动态图演示页面: http://www.cnblogs.com/daysme/p/6790829.html 一个用来展示前端网页demo的小“助手”,提 ...

  9. 1、My Scripts

    1.写一个包含命令.变量和流程控制的语句来清除/var/log的messages日志文件的shell脚本.(P26)(11-21) 2.利用$0和(dirname.basename)取出当前路径的目录 ...

  10. python FAE

    1.python 时间戳用localtime转换时间戳较大时报错 ValueError: timestamp out of range for platform time_t 2.python面向对象 ...