Home  >  Article  >  Web Front-end  >  Tutorial on using stream in node.js

Tutorial on using stream in node.js

高洛峰
高洛峰Original
2016-12-28 13:14:491398browse

I went to learn OC these days, but I haven’t finished it yet. It’s still a long time before I change careers, so let’s review the knowledge of node.

There are many people coming and going in each language, but I can’t live without node. I don't use it for development, I just use js relatively much, so it is better to study node. The status of stream in node is very high. I'll take a look at this content in my spare time. I'm still a newbie on the road to node.

Today I downloaded the nodeschool course to see, there is an example in it. (I modified it a little)

var concat = require('concat-stream');
var http = require('http');
var qs = require('querystring');
 
  var server = http.createServer(function (req, res) {
    if (req.method === 'POST') {
      req.pipe(concat(function (body) {
        body = qs.parse(body.toString())
        res.end(Object.keys(body).join('\n')); 
      }));
    }
    else res.end();
  });
  server.listen(5000);

This question means that you are asked to reverse the post data, but I will not do it. The principle is the same, but the requirements are different. We use the concat plug-in to direct the data flow to concat when the form is submitted. This example is to take the data from the form post.

For testing, I use the request library.

var request = require(‘request')
request.post(‘ http://127.0.0.1:5000 ‘, {form:
 
{
 
“name”: “ryan”,
 
“age” : 23
 
}
 
}, function(err,res,body){
 
console.log(‘接收成功:')
 
console.log(res[‘body']) // name age
 
})

Start the server, and then run the test. You can see that we posted this object. The concat-stream module is mainly used to connect buffers. My understanding is that when you transmit in the form of a buffer, you can transmit any type. In npmjs, it transmits a picture. After we receive it, Then we get the data of this image, and we can use this to upload and copy. The principles are the same.

For more articles related to stream usage tutorials in node.js, please pay attention to the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn