javascript - Node.js 返回文件结果

标签 javascript node.js

我想制作一个 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 并尽早缓存结果,但这行不通,因为在这种情况下“源文件”可能会即时更改。

最佳答案

好的,所以你想让你的开发版本在每次更改时自动加载和重新渲染文件,对吗?

您可以使用 fs.watchFile 来监视文件,然后在每次更改时重新呈现模板,我想您在您的文件中有某种全局变量,它表明服务器是否正在开发或生产模式下运行:

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 属性,如果您在开发模式中,它会在每次更改时自动重新呈现文件。

关于javascript - Node.js 返回文件结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3877915/

相关文章:

javascript - 如何正确测试具有身份验证的 RESTful API

javascript - node.js 限制路由,以便可以使用 jquery 加载但无法通过 url 访问

javascript - 使用 Javascript FileReader API 一次读取多个文件

Javascript if 语句失败

node.js - 如何在mongodb中过滤两次之间的数据

node.js - Socket IO 无限循环超过 1000 个连接

javascript - Gatsby/Netlify 样式不会显示?

javascript - 居中行内 block 元素

javascript - 如何在 JavaScript 中删除字符串中多余的空格?

javascript - 禁用文件上传的 bodyparser - Nodejs