gpt4 book ai didi

javascript - json对象的writestream和express?

转载 作者:太空宇宙 更新时间:2023-11-04 01:03:29 25 4
gpt4 key购买 nike

我可能不够深入,但我确实需要一些东西来工作。我认为写/读流可以解决我的两个问题,但我不太了解语法或它工作所需的内容。我阅读了流手册,并认为我了解了一些基础知识,但当我尝试将其应用到我的情况时,它似乎崩溃了。

目前我将此作为我信息的核心。

function readDataTop (x) {
console.log("Read "+x[6]+" and Sent Cached Top Half");
jf.readFile( "loadedreports/top"+x[6], 'utf8', function (err, data) {
resT = data
});
};

我正在为 Node 使用 Jsonfile 插件,它基本上缩短了 fs.write 并使写入变得更容易,而不是不断地为 fs.write 和 read 编写 catch 和 try block 。

无论如何,我想在这里实现一个流,但我不确定我的 Express 端会发生什么以及如何接收对象。

我认为因为它是一个流表达,所以在收到它之前不会对对象执行任何操作?或者我是否必须编写一个回调来确保当调用我的函数时,在express发送对象以完成ajax请求之前流已完成?

app.get('/:report/top', function(req, res) {
readDataTop(global[req.params.report]);
res.header("Content-Type", "application/json; charset=utf-8");
res.header("Cache-Control", "max-age=3600");
res.json(resT);
resT = 0;
});

我希望如果我将读取部分更改为流,它将减轻两个问题。由于较大的 json 对象的读取速度,浏览器进行 ajax 调用时有时会收到公正的 json 文件的问题。 (这可能是我需要解决的回调问题,但流应该使其更加一致)。

其次,当我加载这个 Node 应用程序时,它需要运行 30 多个写入文件,同时从我的数据库获取数据。目标是断开浏览器与数据库端的连接,以便 Node 通过读写充当数据库。这是由于旧的 SQL 服务器已经受到大量请求的轰炸(过时的数据不是问题)。

这里有语法方面的帮助吗?

我可以在有人将响应管道传输到写入流的代码中看到教程吗? (我使用的 mssql Node 将 SQL 响应放入一个对象中,我需要 JSON 格式)。

function getDataTop (x) {
var connection = new sql.Connection(config, function(err) {
var request = new sql.Request(connection);
request.query(x[0], function(err, topres) {
jf.writeFile( "loadedreports/top"+x[6], topres, function(err) {
if(err) {
console.log(err);
} else {
console.log(x[6]+" top half was saved!");
}
});
});
});
};

最佳答案

您的问题是您在发送响应之前没有等待文件加载。使用回调:

function readDataTop(x, cb) {
console.log('Read ' + x[6] + ' and Sent Cached Top Half');
jf.readFile('loadedreports/top' + x[6], 'utf8', cb);
};

// ...

app.get('/:report/top', function(req, res) {
// you should really avoid using globals like this ...
readDataTop(global[req.params.report], function(err, obj) {
// setting the content-type is automatically done by `res.json()`

// cache the data here in-memory if you need to and check for its existence
// before `readDataTop`

res.header('Cache-Control', 'max-age=3600');
res.json(obj);
});
});

关于javascript - json对象的writestream和express?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25080744/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com