Node.js development stack
03 Jul 2018Node.js development stack
function | projects | |
---|---|---|
package management | npm | |
CSS preprocessors | less, sass | |
JS module loader | require.js, Browserfy | |
JS transpiler | coffee loader, ts-loader |
- ES2015+
- vue
- vuex
- vue-router
- axios
- element-ui
- Mock.js
Node.js
https://www.w3schools.com/nodejs/default.asp
- Node.js uses asynchronous programming!
- Node.js can generate dynamic page content
- Node.js can create, open, read, write, delete, and close files on the server
- Node.js can collect form data
- Node.js can add, delete, modify data in your database
Modules
- What is a Module in Node.js?
Consider modules to be the same as JavaScript libraries.A set of functions you want to include in your application.
- built-in modules
Module | Description |
---|---|
assert | Provides a set of assertion tests |
buffer | To handle binary data |
child_process | To run a child process |
cluster | To split a single Node process into multiple processes |
crypto | To handle OpenSSL cryptographic functions |
dgram | Provides implementation of UDP datagram sockets |
dns | To do DNS lookups and name resolution functions |
domain | Deprecated. To handle unhandled errors |
events | To handle events |
fs | To handle the file system |
http | To make Node.js act as an HTTP server |
https | To make Node.js act as an HTTPS server. |
net | To create servers and clients |
os | Provides information about the operation system |
path | To handle file paths |
punycode | Deprecated. A character encoding scheme |
querystring | To handle URL query strings |
readline | To handle readable streams one line at the time |
stream | To handle streaming data |
string_decoder | To decode buffer objects into strings |
timers | To execute a function after a given number of milliseconds |
tls | To implement TLS and SSL protocols |
tty | Provides classes used by a text terminal |
url | To parse URL strings |
util | To access utility functions |
v8 | To access information about V8 (the JavaScript engine) |
vm | To compile JavaScript code in a virtual machine |
zlib | To compress or decompress files |
-
Include Modules
To include a module, use the require() function with the name of the module:
var http = require('http');
- Create Your Own Modules
// save as mymodule.j* exports.myDateTime = function () { return Date(); };
// in another main.js var mymodule = require('./mymodule') var datetime = mymodule.myDateTime()
- HTTP Module
var http = require('http'); //create a server object: http.createServer(function (req, res) { res.write('Hello World!'); //write a response to the client res.end(); //end the response }).listen(8080);
- Add an HTTP Header
` res.writeHead(200, {‘Content-Type’: ‘text/html’});`
- Read the Query String
res.write(req.url);
- Split the Query String
var q = url.parse(req.url, true).query; var txt = q.year + " " + q.month;
- Add an HTTP Header
- File System Module
- Node.js as a File Server
var fs = require('fs');
- Read Files
fs.readFile('demofile1.html', function(err, data) {
- Create Files
var fs = require('fs'); fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) { if (err) throw err; console.log('Saved!'); });
-
Delete Files
var fs = require('fs'); fs.unlink('mynewfile2.txt', function (err) { if (err) throw err; console.log('File deleted!'); });
- rename files
fs.rename('mynewfile1.txt', 'myrenamedfile.txt', function (err) {
- Upload Files
var formidable = require('formidable');
- Node.js as a File Server
- Send an Email
- nodemailer module
var nodemailer = require('nodemailer');
- multiple receivers
- html
- nodemailer module
- Events module
- addListener()
- defaultMaxListeners
- emit()
- eventNames()
- getMaxListeners()
- listenerCount()
- listeners()
- on()
- once()
- prependListener()
- prependOnceListener()
- removeAllListeners()
- removeListener()
- setMaxListeners()
var events = require('events'); var eventEmitter = new events.EventEmitter(); eventEmitter.on('scream', function() { console.log('A scream is detected!'); }); eventEmitter.emit('scream');
- NPM
- download:
npm install upper-case --save
- use:
var uc = require('upper-case')
- download:
- URL
var url = require('url'); var adr = 'http://localhost:8080/default.htm?year=2017&month=february'; var q = url.parse(adr, true); console.log(q.host); //returns 'localhost:8080' console.log(q.pathname); //returns '/default.htm' console.log(q.search); //returns '?year=2017&month=february' var qdata = q.query; //returns an object: { year: 2017, month: 'february' } console.log(qdata.month); //returns 'february'
Node.js and MySQL
Node.js and MongoDB
- install driver:
npm install mongodb --save
var mongo = require('mongodb');
- create collections
var MongoClient = require('mongodb').MongoClient; var url = "mongodb://localhost:27017/"; MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("mydb"); dbo.createCollection("customers", function(err, res) { if (err) throw err; console.log("Collection created!"); db.close(); }); var myobj = { name: "Company Inc", address: "Highway 37" }; dbo.collection("customers").insertOne(myobj, function(err, res) { if (err) throw err; console.log("1 document inserted"); db.close(); }); });
package.json
- package.json
The package.json file is core to the Node.js ecosystem and is a basic part of understanding and working with Node.js, npm, and even modern JavaScript. The package.json is used as what equates to a manifest about applications, modules, packages, and more - it’s a tool to that’s used to make modern development streamlined, modular, and efficient.
- name
- version
- description
- license
- keywords
- dependencies
- devDependencies
- “main”: “app.js”,
- repository
- scripts
Learn ES2015
https://old.babeljs.io/learn-es2015/
- Arrows and Lexical This
Vue.js
Hello world
- import:
<script src="https://unpkg.com/vue"></script>
- HTML ```html
3. javascript
```js
var app = new Vue({
el: '#app',
data: {
message: 'hello, world'
}
})
HTML 中用一个 mount point <div id="app">
, 在 javascript 创建一个 Vue 示例。
HTML 渲染
- 文本插值: ``
- v-bind:
:title
e.g. ` ` - v-on:
@click
事件处理 ` ` - 条件:
v-if
- 循环:
v-for
- 用户输入:
v-model
: ` `
Component
// 定义名为 todo-item 的新组件
Vue.component('todo-item', {
template: '<li>这是个待办项</li>'
})
Instead, a component’s data option must be a function, so that each instance can maintain an independent copy of the returned data object:
data: function () {
return {
count: 0
}
}
Organizing components
- registration:
- global
Vue.component('name', opts)
- Globally registered components can be used in the template of any root Vue instance (new Vue) created afterwards – and even inside all subcomponents of that Vue instance’s component tree.
- local
- global
- Props
- props is like interface to class, and data is used to maitain interal state, as private fields to class.
-
SFC
Vue.
- Passing Data to Child Components with Props
- Sending Messages to Parents with Events
- v-model
- Content Distribution with Slots
- Dynamic Components
<component v-bind:is="currentTabComponent"></component>
Vue class / instance
var vm = new Vue({
})
Options/*
- el: 锚点
- data: 要绑定的数据
- computed: 复杂属性
- props: 对外的属性接口,类似 C# /Android 中 view 等属性。
- methods: 方法
API
global config
- silent
- optionMergeStrategies
- devtools
- errorHandler
- warnHandler
- ignoredElements
- keyCodes
- performance
- productionTip
Global API
- Vue.extend(options)
- Vue.nextTick([callback, context])
- Vue.set(target, key, value)
- Vue.delete(target, key)
- Vue.directive(id, [definition])
- Vue.filter(id, [definition])
- Vue.component(id, [definition])
- Vue.use(plugin)
- Vue.mixin(mixin)
- Vue.compile(template)
- Vue.version
Options/data
- data
- props: A list/hash of attributes that are exposed to accept data from the parent component.
- propsData: initial / default data for props
- computed:
events
$emit
synthetic events Creating and triggering events
vm.$emit( eventName, […args] )
Questions
- what is javascript prototype?
fdf
- what is javascript context this?
The answer is short and simple: Scope pertains to the visibility of variables, and context refers to the object within which a function is executed.
javascript context/ scope/ this
- context/ this: function
context means this keyword
Context is most often determined by how a function is invoked. When a function is called as a method of an object, this is set to the object the method is called on:
So for a global function, this refers to ‘window’ in browser
- scope: variable
- local
- Global
- block: let/ const
-
Execution Context
- Execution stack
The answer is short and simple: Scope pertains to the visibility of variables, and context refers to the object within which a function is executed.
Vue-cli
https://cli.vuejs.org/
new 3.x is @vue/cli
, the old is vue-cli
- instant prototyping
vue serve
- Create a project
vue create
- Plugins
- Presets
- CLI service
UI
-
UI template
vue ui
vue-cli-service
➜ hello-vue git:(master) ✗ ./node_modules/.bin/vue-cli-service
Usage: vue-cli-service <command> [options]
Commands:
serve start development server
build build for production
inspect inspect internal webpack config
lint lint and fix source files
run vue-cli-service help [command] for usage of a specific command.
- Using the Binary
- vue-cli-service serve
- vue-cli-service build
- vue-cli-service inspect
- Checking All Available Commands
- Caching and Parallelization
- Git Hooks
- Configuration without Ejecting
- webpack-dev-server
MISCS
- UMD
- AMD
- CommonJS is a project with the goal of specifying an ecosystem for JavaScript outside the browser (for example, on the server or for native desktop applications).
vue-loader
是一个 webpack 的 loader,可以将用下面这个格式编写的 Vue 组件转换为 JavaScript 模块:
AMD v.s. CommonJS v.s. UMD
https://www.davidbcalhoun.com/2014/what-is-amd-commonjs-and-umd/
AMD v.s. CommonJS
Sandboxed
Asynchronous Module Definition
- AMD <- RequireJS
// filename: foo.js define(['jquery', 'underscore'], function ($, _) { // methods function a(){}; // private because it's not returned (see below) function b(){}; // public because it's returned function c(){}; // public because it's returned // exposed public methods return { b: b, c: c } });
-
CommonJS <- Browserify
// filename: foo.js var $ = require('jquery'); var _ = require('underscore'); // methods function a(){}; // private because it's omitted from module.exports (see below) function b(){}; // public because it's defined in module.exports function c(){}; // public because it's defined in module.exports // exposed public methods module.exports = { b: b, c: c };
-
UMD: The pattern is admittedly ugly, but is both AMD and CommonJS compatible, as well as supporting the old-style “global” variable definition:
(function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD define(['jquery'], factory); } else if (typeof exports === 'object') { // Node, CommonJS-like module.exports = factory(require('jquery')); } else { // Browser globals (root is window) root.returnExports = factory(root.jQuery); } }(this, function ($) { // methods function myFunc(){}; // exposed public method return myFunc; }));
MISC
- js
===
v.s.==
##
vuex
vuex 集中管理应用中的状态。 类似 Java Spring 中的配置中心。 一种管理的哲学思想 commit 的方式相当于 会隐藏了 setOnListener 的调用, 类似 set 方法, 而不是直接访问状态字段
- state
- mutations
- 触发变化
store.commit('increment')
- 调用状态: 计算属性
computed: { count () { return store.state.count } }
- 单一状态树, 唯一数据源 SSOT, 状态快照
So actions/mutations allow you to:
- centrally define allowed changes to the state, and by that,
- how those changes are connected and logically depend on one another (i.e. by reading an action that commits a series of mutations)
- track these changes in the devtools very easily, as you see all the Mutation names you just read in the list there.
-
writing expressive code that, to an extend, documents your business logic. You can understand a lot about an app’s business logic by just reading its store actions & mutations, without digging through hundreds of components looking where some piece of state is altered under which circumstances.
- mapGetter 类同 Java Bean 中的自动生成 get 函数
- mapMutations 类同 Java Bean 中自动生成 set 函数
- 可以手写 get / set 函数, 以定制化
- get: getters:
- set: mutations:
- mutaions = event + event handler (type + handler)
- computed: mapState
- Actions
- …mapActions
MISC
setInterval
clearInterval
setTimeout
clearTimeout