簡體   English   中英

在node.js中同步加載多個文件

[英]Loading multiple files synchronously in node.js

我正在學習node.js,並圍繞MVC架構構建了一個微型應用程序。

我有一個router.js文件,該文件基於URI加載控制器,在大多數情況下,該文件將使用“ fs”模塊加載視圖。 視圖是構成網頁的HTML元素(基本上是頭部,正文和頁腳),為3個單獨的文件

這是控制器的代碼:

var load_view = 'test.html';

function data(response, request, fs){ 

    response.writeHead(200, {"Content-Type": "text/html"});

    var count = 0;
    var handler = function(error, content){

        count++;
        if(error)   console.log(error);
        else        response.write(content);

        if(count==3) response.end();

    }

    fs.readFile('view/elements/head.html', handler);  // should load 1st
    fs.readFile('view/'+load_view, handler);          // should load 2nd
    fs.readFile('view/elements/footer.html', handler);// should load 3rd

}

exports.data = data;

如您所見,應該按順序加載HTML元素(head.html,然后是該控制器的特定視圖-test.html,然后是footer.html)。 但是他們有時不這樣做。

它們大部分時間按“頭,身體,頁腳”順序加載。

有時,它們以“頭,頁腳,身體”的形式加載。

其他時候是“身體,頭部,頁腳”。

它們似乎從未加載任何其他配置。

請參閱所附的屏幕截圖。

頭,身體,頁腳

頭,頁腳,身體

身體,頭部,頁腳

我不確定這里發生了什么。 為什么這些文件以任何順序加載,但它們被稱為?

  • 請注意,我並不是出於學習目的而使用Express.js之類的框架

您不能假設異步請求的響應順序。 有多種因素可能影響此排序(例如,在文件系統請求的情況下,OS線程調度)。

因此,解決方案是通過嵌套回調或鏈接Promises或使用諸如async類的模塊來串行調用它們,或者將回調綁定為包含相關的上下文信息,以便您知道哪個文件剛剛加載到回調中。 后者的示例可能是這樣的:

function data(res, req, fs) {
  // Files to be loaded, in the order to be written to the response
  var files = [
    'view/elements/head.html',
    'view/' + load_view,
    'view/elements/footer.html'
  ];

  // Start read requests, each with a callback that has an extra
  // argument bound to it so it will be unshifted onto the callback's
  // parameter list
  for (var i = 0; i < files.length; ++i)
    fs.readFile(files[i], handler.bind(null, i));

  var count = 0;
  function handler(index, err, content) {
    // Make sure we don't send more than one response on error
    if (count < 0)
      return;

    if (err) {
      count = -1;
      console.log('Error for file: ' + files[index]);
      console.log(err);
      res.writeHead(500);
      return res.end();
    }

    // Reuse our `files` array by simply replacing filenames with
    // their respective content
    files[index] = content;

    // Check if we've read all the files and write them in order if
    // we are finished
    if (++count === files.length) {
      res.writeHead(200, { 'Content-Type': 'text/html' });
      for (var i = 0; i < files.length; ++i)
        res.write(files[i]);
      res.end();
    }
  }
}

在相關說明中,您可能會考慮使用某種模板系統(該模板系統支持包括部分內容(如頁眉和頁腳)和布局),以避免進行此類手動工作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM