这是我之前问的问题的扩展。
我正在从基于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);
}
运行代码也会产生此错误消息:
(节点:15672)UnhandledPromiseRejectionWarning:未处理的承诺 拒绝。该错误是由抛出异步内部引起的 没有捕获块或拒绝承诺 未使用.catch()处理。 (拒绝ID:1)(节点:15672)[DEP0018] DeprecationWarning:已弃用未处理的承诺拒绝。在 未来,未处理的承诺拒绝将终止 具有非零退出代码的Node.js进程。
更新。
我添加了尝试,捕获到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
}
}
}
答案 0 :(得分:0)
您是否尝试将writeData调用包装在try catch语句中?
try {
writeData();
} catch (error) {
//
}
答案 1 :(得分:0)
似乎变量boxers
不是数组。该错误表明rows.reduce is not a function
和您正在传递boxers
变量作为rows参数。
在调用write函数检查boxers变量是否为数组之前,请添加console.log或debug。我猜这行
var boxers = await boxrec.getPersonById(cookieJar,356831);
不返回数组。