簡體   English   中英

Node.js返回文件的結果

[英]Node.js return result of file

我想創建一個node.js函數,當調用時,它會讀取一個文件並返回內容。 我這樣做有困難,因為'fs'被解雇了。 因此,我的功能必須如下所示:

function render_this() {
    fs.readFile('sourcefile', 'binary', function(e, content) {
        if(e) throw e;
        // I have the content here, but how do I tell people?
    });
    return /* oh no I can't access the contents! */;
};

我知道可能有一種方法可以使用非事件IO來做到這一點,但我更喜歡一個允許我等待事件函數的答案,這樣如果我遇到需要的情況,我就不會再次陷入困境做同樣的事情,但沒有IO。 我知道這打破了“一切都是好事”的想法,而且我不打算經常使用它。 但是,有時我需要一個實用功能,可以動態呈現haml模板。

最后,我知道我可以調用fs.readFile並盡早緩存結果,但這不起作用,因為在這種情況下'sourcefile'可能會動態更改。

好的,所以你想讓你的開發版本在每次更改時自動加載和重新呈現文件,對吧?

您可以使用fs.watchFile監視文件,然后在每次更改時重新呈現模板,我想您已經有了某種全局變量,其中說明服務器是以dev還是生產模式運行:

var fs = require('fs');
var http = require('http');
var DEV_MODE = true;

// Let's encapsulate all the nasty bits!
function cachedRenderer(file, render, refresh) {
    var cachedData = null;
    function cache() {

        fs.readFile(file, function(e, data) {
            if (e) {
                throw e;
            }
            cachedData = render(data);
        });

        // Watch the file if, needed and re-render + cache it whenever it changes
         // you may also move cachedRenderer into a different file and then use a global config option instead of the refresh parameter
        if (refresh) {
            fs.watchFile(file, {'persistent': true, 'interval': 100}, function() {
                cache();
            });
            refresh = false;
        }
    }

    // simple getter
    this.getData = function() {
        return cachedData;
    }

    // initial cache
    cache();
}


var ham = new cachedRenderer('foo.haml',

    // supply your custom render function here
    function(data) {
        return 'RENDER' + data + 'RENDER';
    },
    DEV_MODE
);


// start server
http.createServer(function(req, res) {
    res.writeHead(200);
    res.end(ham.getData());

}).listen(8000);

創建一個cachedRenderer ,然后在需要時訪問它的getData屬性,如果你處於開發模式,它會在每次更改時自動重新呈現文件。

function render_this( cb ) {
    fs.readFile('sourcefile', 'binary', function(e, content) {
        if(e) throw e;
        cb( content );
    });
};


render_this(function( content ) {
  // tell people here
});

暫無
暫無

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

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