Node.js 向用戶端發送流資料

來源:互聯網
上載者:User

Node.js 向用戶端發送流資料
如果某個被請求的頁面資料比較大,或者是一個需要一定時間來完成的資料流,那麼以流的方式把已經完成的資料發送給用戶端是一個比較好的做法。在express中,一般的做法是等資料完成之後,統一發送,如使用exec執行系統命令時,之後在命令結束之後,才會調用回呼函數處理命令輸出。

  1. function cmd(command,req,callback) {
  2. var sys = require('sys')
  3. var exec = require('child_process').exec;
  4. console.log(new Date() + ' Run command from ' + req.ip);
  5. console.log(command);

  6. exec(command, {
  7. maxBuffer: 2000 * 1024
  8. }, function (error, stdout, stderr) {
  9. callback(stdout.trim());
  10. })
  11. }
以下的幾種方式可以用來實現流式的資料轉送。


持續寫res方式
最直白的方式就是持續寫入node的res對象,例如:
  1. var sys = require('sys'),
  2. http = require('http');
  3. http.createServer(function (req, res) {
  4. res.writeHead(200, {'Content-Type': 'text/html'});
  5. var currentTime = new Date();
  6. sys.puts('Starting sending time');
  7. setInterval(function(){
  8. res.write(
  9. currentTime.getHours()
  10. + ':' +
  11. currentTime.getMinutes()
  12. + ':' +
  13. currentTime.getSeconds() + "\n"
  14. );

  15. setTimeout(function() {
  16. res.end();
  17. }, 10000);

  18. },1000);
  19. }).listen(8090, '192.168.175.128');
但是這種方法的缺點很多,首先express架構中被封裝的res對象不支援這種方式的使用,更嚴重的是只有支援“XHR.readyState = 3 (partial response)”的瀏覽器才能這麼用。另外有人建議使用Sockets.io,有興趣的朋友可以試試。
  1. WebSocket
  2. WebSocket over Flash (+ XML security policy support)
  3. XHR Polling
  4. XHR Multipart Streaming
  5. Forever Iframe
  6. JSONP Polling (for cross domain)


使用stream對象的pipe
類似於 *nix 將幾乎所有裝置抽象為檔案一樣,Node 將幾乎所有 IO 操作都抽象成了 Stream 的操作。Stream 是一個抽象的概念,總之就是會冒資料(以 Buffer 為單位),或者能夠吸收資料的東西。

下面是上文系統命令執行的另一個例子,其中使用的spawn的stdout流:
  1. function cmd_stream(command,req,res) {
  2. console.log(new Date() + ' Run command stream from ' + req.ip);
  3. console.log(command);
  4. var spawn = require('child_process').spawn;

  5. var params = command.split(/\s+/);
  6. command = params.shift();
  7. var cmd_process = spawn(command,params);

  8. cmd_process.stderr.pipe(res);
  9. }
另一個檔案流pipe的例子:
  1. function file_stream(file,req,res) {
  2. console.log(new Date() + ' Run readfile stream from ' + req.ip);
  3. var fs = require('fs');
  4. var rstream = fs.createReadStream('/tmp/myfile');
  5. // var rstream = fs.createReadStream(file);
  6. rstream.pipe(res);
  7. }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.