Published on

Node.js development stack

Authors

Node.js development stack

functionprojects
package managementnpm
CSS preprocessorsless, sass
JS module loaderrequire.js, Browserfy
JS transpilercoffee 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

ModuleDescription
assertProvides a set of assertion tests
bufferTo handle binary data
child_processTo run a child process
clusterTo split a single Node process into multiple processes
cryptoTo handle OpenSSL cryptographic functions
dgramProvides implementation of UDP datagram sockets
dnsTo do DNS lookups and name resolution functions
domainDeprecated. To handle unhandled errors
eventsTo handle events
fsTo handle the file system
httpTo make Node.js act as an HTTP server
httpsTo make Node.js act as an HTTPS server.
netTo create servers and clients
osProvides information about the operation system
pathTo handle file paths
punycodeDeprecated. A character encoding scheme
querystringTo handle URL query strings
readlineTo handle readable streams one line at the time
streamTo handle streaming data
string_decoderTo decode buffer objects into strings
timersTo execute a function after a given number of milliseconds
tlsTo implement TLS and SSL protocols
ttyProvides classes used by a text terminal
urlTo parse URL strings
utilTo access utility functions
v8To access information about V8 (the JavaScript engine)
vmTo compile JavaScript code in a virtual machine
zlibTo 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.js
    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
      
  • 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')
      
  • Send an Email

    • nodemailer module var nodemailer = require('nodemailer');

    • multiple receivers

    • html

  • 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')

  • 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

  1. import: <script src="https://unpkg.com/vue"></script>
  2. HTML
{{ message }}
  1. javascript
var app = new Vue({
  el: '#app',
  data: {
    message: 'hello, world',
  },
})

HTML 中用一个 mount point <div id="app"> , 在 javascript 创建一个 Vue 示例。

HTML 渲染

  1. 文本插值: {{Message}}
  2. v-bind: :title e.g. <span v-bind:title="message">
  3. v-on: @click 事件处理 <button v-on:click="reverseMessage">逆转消息</button>
  4. 条件: v-if
  5. 循环: v-for
  6. 用户输入: v-model : <input v-model="message">

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

  • Props

    • props is like interface to class, and data is used to maintain internal 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/*

  1. el: 锚点
  2. data: 要绑定的数据
  3. computed: 复杂属性
  4. props: 对外的属性接口,类似 C# /Android 中 view 等属性。
  5. 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

  1. what is javascript prototype?

    fdf

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

    Understanding Scope and Context in JavaScript

  • 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

img

  • 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

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