Node.js: CP5

百里金林
2023-12-01

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');
 类似资料:

相关阅读

相关文章

相关问答