Node. js sends streaming data to the client
If the data on a requested page is large or a data stream that takes some time to complete, it is better to send the completed data to the client in the form of a stream. In express, the general practice is to send data after the data is completed. For example, when the system command is executed using exec, the callback function is called to process the command output after the command is completed.
- Function cmd (command, req, callback ){
- Var sys = require ('sys ')
- Var exec = require('child_process'cmd.exe c;
- Console. log (new Date () + 'run command from '+ req. ip );
- Console. log (command );
- Exec (command ,{
- MaxBuffer: 2000*1024
- }, Function (error, stdout, stderr ){
- Callback (stdout. trim ());
- })
- }
The following methods can be used to transmit streaming data.
Continuous write res Mode
The most straightforward method is to continuously write the res object of node, for example:
- Var sys = require ('sys '),
- Http = require ('http ');
- Http. createServer (function (req, res ){
- Res. writeHead (200, {'content-type': 'text/html '});
- Var currentTime = new Date ();
- Sys. puts ('starting sending Time ');
- SetInterval (function (){
- Res. write (
- CurrentTime. getHours ()
- + ':' +
- CurrentTime. getMinutes ()
- + ':' +
- CurrentTime. getSeconds () + "\ n"
- );
- SetTimeout (function (){
- Res. end ();
- },10000 );
- },1000 );
- }). Listen (8090, '192. 168.175.128 ');
However, this method has many disadvantages. First, the packaged res objects in the express framework do not support this method. More seriously, it only supports "XHR. readyState = 3 (partial response. Someone also suggested using Sockets. io. If you are interested, you can try it.
- WebSocket
- WebSocket over Flash (+ XML security policy support)
- XHR Polling
- XHR Multipart Streaming
- Forever Iframe
- JSONP Polling (for cross domain)
Use pipe of stream Object
Similar to * nix, which abstracts almost all devices into files, Node abstracts almost all IO operations into Stream operations. Stream is an abstract concept. In short, Stream can take data (in Buffer units) or absorb data.
The following is another example of system command execution, where the stdout stream of spawn is used:
- Function performance_stream (command, req, res ){
- Console. log (new Date () + 'run command stream from' + req. ip );
- Console. log (command );
- Var spawn = require ('child _ Process'). spawn;
- Var params = command. split (/\ s + /);
- Command = params. shift ();
- Var cmd_process = spawn (command, params );
- Pai_process.stderr.pipe (res );
- }
An example of another file stream pipe:
- Function file_stream (file, req, res ){
- Console. log (new Date () + 'run readfile stream from' + req. ip );
- Var fs = require ('fs ');
- Var rstream = fs. createReadStream ('/tmp/myfile ');
- // Var rstream = fs. createReadStream (file );
- Rstream. pipe (res );
- }