Skip to content

01-event-1.js

javascript
const http = require('http')
let request = {
  get url() {
    return this.req.url
  },
}
let response = {
  get body() {
    return this._body
  },
  set body(val) {
    this._body = val
  },
}

let context = {
  get url() {
    return this.request.url
  },
  get body() {
    return this.response.body
  },
  set body(val) {
    this.response.body = val
  },
}
class Application {
  constructor() {
    // this.callback = () => {}
    this.context = context
    this.request = request
    this.response = response
    this.middlewares = []
  }
  use(callback) {
    this.middlewares.push(callback)
    // this.callback = callback;
  }
  compose(middlewares) {
    return function (context) {
      return dispatch(0)

      function dispatch(i) {
        let fn = middlewares[i]
        if (!fn) {
          return Promise.resolve()
        }
        return Promise.resolve(
          fn(context, function next() {
            return dispatch(i + 1)
          })
        )
      }
    }
  }
  listen(...args) {
    const server = http.createServer(async (req, res) => {
      let ctx = this.createCtx(req, res)
      // await this.callback(ctx);
      const fn = this.compose(this.middlewares)
      await fn(ctx)
      ctx.res.end(ctx.body)
      // this.callback(req, res);
    })
    server.listen(...args)
  }
  createCtx(req, res) {
    let ctx = Object.create(this.context)
    ctx.request = Object.create(this.request)
    ctx.response = Object.create(this.response)
    ctx.req = ctx.request.req = req
    ctx.res = ctx.response.res = res
    return ctx
  }
}

module.exports = Application

02-stream-1.js

javascript
var fs = require('fs')
var readStream = fs.createReadStream('./data/file1.txt') // 读取文件的 Stream

var length = 0
readStream.on('data', function (chunk) {
  length += chunk.toString().length
})
readStream.on('end', function () {
  console.log(length)
})

02-stream-2.js

javascript
var readline = require('readline')
var fs = require('fs')

var rl = readline.createInterface({
  input: fs.createReadStream('./data/file1.txt'),
})

var lineNum = 0
rl.on('line', function (line) {
  lineNum++
})
rl.on('close', function () {
  console.log('lineNum', lineNum)
})

02-stream-3.js

javascript
var http = require('http')

function serverCallback(req, res) {
  var method = req.method.toLowerCase() // 获取请求的方法
  if (method === 'get') {
  }
  if (method === 'post') {
    // 接收 post 请求的内容
    var data = ''
    req.on('data', function (chunk) {
      // “一点一点”接收内容
      console.log('chunk', chunk.toString())
      data += chunk.toString()
    })
    req.on('end', function () {
      // 接收完毕,将内容输出
      console.log('end')
      res.writeHead(200, { 'Content-type': 'text/html' })
      res.write(data)
      res.end()
    })
  }
}
http.createServer(serverCallback).listen(8081) // 注意端口别和其他 server 的冲突
console.log('监听 8081 端口……')

03-genarator-1.js

javascript
function* helloWorldGenerator() {
  yield 'hello'
  yield 'world'
  return 'ending'
}

var hw = helloWorldGenerator()
console.log(hw.next())
console.log(hw.next())
console.log(hw.next())
console.log(hw.next())

function* foo() {
  yield 1
  yield 2
  yield 3
  yield 4
  yield 5
  return 6
}

for (let v of foo()) {
  console.log(v)
}

application.js

javascript
const http = require('http')
let request = {
  get url() {
    return this.req.url
  },
}
let response = {
  get body() {
    return this._body
  },
  set body(val) {
    this._body = val
  },
}

let context = {
  get url() {
    return this.request.url
  },
  get body() {
    return this.response.body
  },
  set body(val) {
    this.response.body = val
  },
}
class Application {
  constructor() {
    // this.callback = () => {}
    this.context = context
    this.request = request
    this.response = response
    this.middlewares = []
  }
  use(callback) {
    this.middlewares.push(callback)
    // this.callback = callback;
  }
  compose(middlewares) {
    return function (context) {
      return dispatch(0)

      function dispatch(i) {
        let fn = middlewares[i]
        if (!fn) {
          return Promise.resolve()
        }
        return Promise.resolve(
          fn(context, function next() {
            return dispatch(i + 1)
          })
        )
      }
    }
  }
  listen(...args) {
    const server = http.createServer(async (req, res) => {
      let ctx = this.createCtx(req, res)
      // await this.callback(ctx);
      const fn = this.compose(this.middlewares)
      await fn(ctx)
      ctx.res.end(ctx.body)
      // this.callback(req, res);
    })
    server.listen(...args)
  }
  createCtx(req, res) {
    let ctx = Object.create(this.context)
    ctx.request = Object.create(this.request)
    ctx.response = Object.create(this.response)
    ctx.req = ctx.request.req = req
    ctx.res = ctx.response.res = res
    return ctx
  }
}

module.exports = Application

server.js

javascript
// const http = require("http");

// const server = http.createServer((req, res) => {
// 	res.writeHead(200);
// 	res.end("Hello WuChenDi");
// });

// server.listen(9092, () => {
// 	console.log("server start on port 9092");
// });

const Dia = require('./application')
const app = new Dia()

function delay() {
  return new Promise((reslove, reject) => {
    setTimeout(() => {
      reslove()
    }, 2000)
  })
}

app.use(async (ctx, next) => {
  ctx.body = '1'
  await next()
  ctx.body += '2'
})
app.use(async (ctx, next) => {
  ctx.body += '3'
  await delay()
  await next()
  ctx.body += '4'
})
app.use(async (ctx, next) => {
  ctx.body += '5'
})
// app.use((req, res) => {
// 	res.writeHead(200);
// 	res.end("Hello WuChenDi");
// });

app.listen(9092, () => {
  console.log('server runing on port 9092')
})

test.js

javascript
// let digot = {
// 	_name: "Di-got",
// 	get name() {
// 		// console.log('value')
// 		// return '你好'
// 		return this._name;
// 	},
// 	set name(val) {
// 		console.log("new name is " + val);
// 		this._name = val;
// 	},
// };

// console.log(digot.name);
// digot.name = "wuchendi";
// console.log(digot.name);

// function add(x, y) {
// 	return x + y;
// }

// function double(z) {
// 	return z * 2;
// }
// const res1 = add(1, 2);
// const res2 = double(res1);
// console.log(res2);

// const res3 = double(add(1, 2));
// console.log(res3);

// function add(x, y) {
// 	return x + y;
// }

// function double(z) {
// 	return z * 2;
// }
// const middlewares = [add, double];
// let len = middlewares.length;

// function compose(midds) {
// 	return (...args) => {
// 		// 初始值
// 		let res = midds[0](...args);
// 		for (let i = 1; i < len; i++) {
// 			res = midds[i](res);
// 		}
// 		return res;
// 	};
// }
// const fn = compose(middlewares);
// const res = fn(1, 2);
// console.log(res);

async function fn1(next) {
  console.log('fn1')
  await next()
  console.log('end fn1')
}

async function fn2(next) {
  console.log('fn2')
  await delay()
  await next()
  console.log('end fn2')
}

async function fn3(next) {
  console.log('fn3')
}

function delay() {
  return new Promise((reslove, reject) => {
    setTimeout(() => {
      reslove()
    }, 2000)
  })
}

function compose(middlewares) {
  return function () {
    return dispatch(0)

    function dispatch(i) {
      let fn = middlewares[i]
      if (!fn) {
        return Promise.resolve()
      }
      return Promise.resolve(
        fn(function next() {
          return dispatch(i + 1)
        })
      )
    }
  }
}

const middlewares = [fn1, fn2, fn3]
const finalFn = compose(middlewares)
finalFn()