Node.js: CP5

req

  • req.url: host名之后的所有内容. e.g. http://localhost:4200/url --> req.url = /url
  • req.method: http method. i.e. GET, POST, PUT DELETE
        var body = '';
        
        req.on('data', function(chunk){
            body += chunk;
        });

        req.on('end', function(){
            res.writeHead(200,{'Content-Type': 'text/plain'});
            res.end(qs.parse(body).name);
        });

querystring

  • 将查询字符串转为JS对象
  • Importing
    require('querystring');
  • qs.parse: Parses the querystring and returns an object
qs.parse(body).name // parse query string named "body" and access 'name' attribute

Process 全局变量

3个stream对象:

  • stdin
  • stdout
  • stderr

process.argv

包含node运行时的参数值

  • 第一个元素: 'node'
  • 第二个元素: 执行文件路径
  • 其他命令行参数

process.cwd()

获取当前的运行目录(工作目录)

e.g.在桌面运行document中的index.js,cwd返回桌面,__dirname返回document

**__dirname: 获取文件保存的目录

process.chdir()

更改工作目录

process.env

环境变量

process.env.NODE_ENV

  • production -- 产品模式
  • development -- 开发模式

process.exit(x)

强制退出

x:退出代码

EventEmitter

监听 or 分发 events

  • non-blocking -- node不会一次性返回data,而是以分发的方式传递数据

监听

a = new EventEmitter();
a.on('某一事件', function{
    //做些什么
})
a = new EventEmitter();
a.once('某一事件', function{
    //做些什么
})

** Once不管事件发生几次,都只监听一次

监听request data

Node sends its data using stream API, that is, in chunks.

Therefore, the best way to access data is collect them in an array, then at the 'end', concatenate and stringify it --

  • listen to the 'data' event (for incoming chunk) -- 会触发很多次
  • listen to the 'end' event (for end of stream) -- 只会触发一次
a = new EventEmitter();
a.on('data', function{
    //做些什么
})

a.on('end', function{
    //做些什么
})

分发

a = new EventEmitter;
a.emit('event');
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值