【发布时间】:2020-02-29 13:20:39
【问题描述】:
这是我上一个问题的扩展。
我正在从基于 node.js 的 API 获取一些数据。
我想将此数据保存到 csv。我遇到的问题是我从 API 获取数据并验证了这一点(console.log 显示了这一点)。 csv 也在创建中,但问题是 csv 中没有任何内容,它是一个空白 csv。
这是我写的代码;
const boxrec = require("boxrec").Boxrec;
const fastcsv = require('fast-csv');
const fs = require('fs');
async function getCookieJar(){
try {
const cookieJar = await boxrec.login('***','******');
return cookieJar;
} catch (e) {
console.log("Login error: " + e);
}
};
async function writeData() {
const cookieJar = await getCookieJar();
var boxers = await boxrec.getPersonById(cookieJar,356831);
const ws = fs.createWriteStream("C:\\Users\\User\\Documents\\testing2.csv");
fastcsv
.write(boxers, {headers: true })
.pipe(ws);
};
try {
writeData();
} catch (error) {
console.log("Error in function " + error);
}
运行代码也会产生这个错误信息:
(node:15672) UnhandledPromiseRejectionWarning: 未处理的承诺 拒绝。此错误源于在异步内部抛出 没有 catch 块的函数,或者通过拒绝一个承诺 不使用 .catch() 处理。 (拒绝 ID:1)(节点:15672)[DEP0018] DeprecationWarning:不推荐使用未处理的承诺拒绝。在 未来,未处理的承诺拒绝将终止 具有非零退出代码的 Node.js 进程。
更新。
我添加了 try, catch 到 writeData,这是我收到的错误消息:
(node:4264) UnhandledPromiseRejectionWarning: TypeError: rows.reduce is not a function
at Object.exports.write (C:\Users\User\node_modules\fast-csv\build\src\formatter\index.js:20:10)
at writeData (C:\Users\User\Documents\index.js:17:6)
(node:4264) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:4264) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
console.log(boxers) 返回:
r {
'$': [Function: initialize] {
fn: initialize { constructor: [Circular], _originalRoot: [Object] },
load: [Function],
html: [Function],
xml: [Function],
text: [Function],
parseHTML: [Function],
root: [Function],
contains: [Function],
merge: [Function],
_root: {
type: 'root',
name: 'root',
namespace: 'http://www.w3.org/1999/xhtml',
attribs: [Object: null prototype] {},
'x-attribsNamespace': [Object: null prototype] {},
'x-attribsPrefix': [Object: null prototype] {},
children: [Array],
parent: null,
next: null
},
_options: {
withDomLvl1: true,
normalizeWhitespace: false,
xml: false,
decodeEntities: true
}
}
}
【问题讨论】:
-
请在 writeData 周围添加一个 try catch。添加一个 console.log 以输出您收到的错误并发布错误输出。
-
@MohitMutha 添加了新的错误输出
标签: node.js