【问题标题】:Delay on file read on newly created file in node.js在 node.js 中新创建的文件上读取文件的延迟
【发布时间】:2017-10-06 00:00:15
【问题描述】:

当我运行我的 results.html 页面时,我正在编写一个新的 json 文件,然后使用 express.static 使公用文件夹文件可以在浏览器中访问。

我的应用程序正在运行,但必须多次单击该按钮才能写入和访问更新的文件。

我应该如何在不写入文件的情况下将 JSON 信息发送到浏览器?或者没有经历过这种滞后?

【问题讨论】:

  • 尝试改用 POST 吗?
  • 这些实际上是 两行 代码!你真的不能包含它们而不是使用屏幕截图吗?

标签: javascript html json node.js express


【解决方案1】:

发回数据作为响应

function setData(req, res) {
    var data = '';

    req.on('data', function(streamData) {
        data += streamData;
    });

    req.on('end', function() {
        fs.writeFile('data/data.json', data, 'utf8', function(err) {
            if (!err) {
                res.writeHead(201, {
                    'Content-Type': 'text/json'
                });
                res.end(data)
            } else {
                res.writeHead(400, {
                    'Content-Type': 'text/json'
                });
                res.end("File write error" + err)
            }
        })
    })
}

从前端访问数据

$.ajax({
        url: '/set/data',
        method: 'POST',
        data: data
    })
    .done(function(responseData) {
        // update your ui with responseData
    })
    .fail(function(error) {
        console.log(error)
    })

【讨论】:

    猜你喜欢
    • 2016-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 2012-06-14
    • 2019-11-29
    • 2013-08-25
    • 2021-01-14
    相关资源
    最近更新 更多