我正在将 oracledb 与 Node 一起使用,并从中异步获取数据。为了方便起见,我使用如下所示的单独文件来实现它 -
config.js -
module.exports = {
user : "user",
password : "password",
connectString : "*connstring*" ,
deliveredQuery: " SELECT COUNT (DISTINCT order_num) AS Cnt from orders where department = 'HR'
};
query2.js:
module.exports = function(callback) {//pass callback function and return with this
var oracledb = require('oracledb');
var dbConfig = require('./config.js');
this.queryDB = function(query,callback) {
oracledb.getConnection({
user: dbConfig.user,
password: dbConfig.password,
connectString: dbConfig.connectString,
deliveredQuery: dbConfig.deliveredQuery
}, function(err, connection) {
if (err) {
console.error(err.message);
return callback(err);
}
connection.execute(query, function(err, result) {
if (err) {
console.error(err.message);
doRelease(connection);
return;
}
//console.log(result.metaData);
//console.log(JSON.parse(result.rows[0][0]));
doRelease(connection);
return callback(null, JSON.parse(result.rows[0][0]))
});
});
function doRelease(connection) {
connection.release(function(err) {
if (err) {
console.error(err.message);
return callback(err);
}
});
}
};
};
serv_ontime.js:
var dbConfig = require('./config.js');
var res = require('./query2.js')();
var onTime_query = dbConfig.onTime_query;
module.exports = queryDB(onTime_query, function(err, callback){ });
index.js:
var res = require('./serv_ontime.js');
console.log("The result is= "+ res);
现在,当我从 cmd 执行 - node index.js 时,我得到的输出为 [object Object]。我想这是因为调用是异步发生的。但是,如果您在文件 query2.js 中看到,我在解析后返回值(使用 JSON.parse),但我在 index.js 文件中获取的值仍然不是解析后的值。 如何解析index.js中的值?我已经尝试过JSON.parse,但它不起作用。
最佳答案
您得到的输出为[object Object]
,因为您正在对字符串执行+
('The result is= '
),因此js引擎尝试将Object
转换为String
。要将其视为对象
,请单独记录它或用逗号分隔记录,
console.log('The result is= ', res); (or)
console.log(res); // or console.dir(res)
或者你可以通过执行JSON.stringify(res)
console.log('The result is= ', JSON.stringify(res));
关于javascript - 解析 Node oracledb 的 JSON 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42761785/