json - NodeJS JSON 应该是全局的,但它是本地的

标签 json node.js express ejs

我正在使用nodeJS Express ejs。我的 JSON 有问题,在渲染我的 ejs 文件之前未填充数据。

app.get('/', function(req, res) { 
    fs.readFile('somepath', 'utf8', function(errRead, data) { 
        var obj;
        if(errRead) { 
            obj = {loaded : false};
        } else {
            var nbCam = 0;
            fs.readFile('somepath', 'utf8', function(errRead, data) {
                if(errRead) throw errRead; 
                for(var i in JSON.parse(data).currentAcquisitionSet) {
                    ++nbCam;
                }
                obj = {loaded : nbCam, images : JSON.parse(data).images};
            });
        }
        console.log(obj); // why is it undefined here?
        res.render('a.ejs', obj);});
    });
});

看起来我的 obj 是一个局部变量,但我不明白为什么。

最佳答案

在将 obj 记录为 fs.readFile 后,将调用 fs.readFile回调 异步

如果您确实想以同步方式读取数据,则可以使用 fs.readFileSync ,或将渲染更改为回调内

app.get('/', function(req, res, next) { 
    fs.readFile('somepath', 'utf8', function(errRead, data) { 
        var obj;
        if(errRead) { 
            obj = {loaded : false};
            res.render('a.ejs', obj);
            return;
        } 
        fs.readFile('somepath', 'utf8', function(errRead, data) {
            if(errRead) {
                return next(errRead);
            }
            var nbCam = 0;
            for(var i in JSON.parse(data).currentAcquisitionSet) {
                ++nbCam;
            }
            obj = {loaded : nbCam, images : JSON.parse(data).images};
            console.log(obj);
            res.render('a.ejs', obj);
        });
    });
});

关于json - NodeJS JSON 应该是全局的,但它是本地的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45031915/

相关文章:

javascript - 如何修改或更改 JSON 数组中的特定对象?

javascript - ExpressJS : Redirect to an URL handled by client-side

node.js - Node js快速路由所有路径

node.js - 如何修复启动 Express 服务器时出现的 Implicit textOnly 消息?

node.js - 创建 React 应用程序 http-proxy-middleware 不工作

json - 在 Spring 中将 pojo 转换为 JSON 的最佳方法是什么

python - 弹性 map 减少误差

javascript - lodash/下划线;比较两个对象并删除重复项

javascript - React + backend - 共享代码时的项目结构

javascript - Mocha "describe"未定义