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);
});
- 将查询字符串转为JS对象
require('querystring');
qs.parse(body).name // parse query string named "body" and access 'name' attribute
3个stream对象:
- stdin
- stdout
- stderr
process.argv
包含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');