我在NodeJS中使用mssql来获取大量行。
我想在Express中将结果传递给HTTP响应,但我看不出如何实现这一点。
db.js
const sql = require('mssql');
const config = {
user: 'user',
password: 'pass',
server: 'host',
database: 'db',
};
index.js
我能够将结果传输到命令行:
router.get('/', function (req, res, next) {
new sql.ConnectionPool(config).connect().then(pool => {
const request = new sql.Request(pool);
request.stream = true;
request.query(`SELECT col1, col2 FROM mytable`);
request.on('row', row => {
console.log(row);
});
});
});
module.exports = router;
但是,使用request.pipe()会导致错误:
router.get('/', function (req, res, next) {
new sql.ConnectionPool(config).connect().then(pool => {
const request = new sql.Request(pool);
request.pipe(res);
request.query(`SELECT col1, col2 FROM mytable`);
request.on('finish', () => {
res.end();
});
});
});
_http_outgoing.js:647 抛出新的错误.TypeError('ERR_INVALID_ARG_TYPE','第一个参数', ^
TypeError [ERR_INVALID_ARG_TYPE]:第一个参数必须是其中之一 输入字符串或缓冲区 在write_(_http_outgoing.js:647:11) 在ServerResponse.write(_http_outgoing.js:622:10) 在Request.emit(events.js:180:13
答案 0 :(得分:0)
编辑:如果您关心流媒体,为什么不将它存储在对象中
router.get('/', function (req, res, next) {
new sql.ConnectionPool(config).connect().then(pool => {
const request = new sql.Request(pool);
request.stream = true;
request.query(`SELECT col1, col2 FROM mytable`);
var output = [];
request.on('row', row => {
console.log(row);
output.push(row)
});
request.on('finish', () => {
res.send(output);
});
});
});
答案 1 :(得分:-1)
app.get("/", (req, res) => {
new sql.ConnectionPool(config).connect().then(pool => {
const request = new sql.Request(pool);
request.stream = true;
request.query('select * from tableName');
request.on("row", async (row) => {
if (
!res.write(JSON.stringify(row), (err) => {
if (err) {
console.error("Failed to send data");
}
})
) {
request.pause();
await new Promise((resolve) => res.once("drain", resolve));
request.resume();
}
});
request.on("error", (err) => {
res.status(500).send({ message: err });
res.end();
});
request.on("done", (result) => {
res.end();
console.log("Data sending complete");
});
});
});