生成空白 csv 输出的函数
这是我之前问过的一个问题的扩展。
我从基于 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: 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:15672) [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.
更新。
我在 writeData 中添加了 try、catch,这是我收到的错误消息:
(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 语句中?
try {
writeData();
} catch (error) {
//
}
似乎变量
boxers
不是数组。错误表明
rows.reduce 不是函数
,而您正在将
boxers
变量作为 rows 参数传递。
请在调用写入函数之前添加 console.log 或调试,以检查 boxers 变量是否是数组。我猜行
var boxers = await boxrec.getPersonById(cookieJar,356831);
没有返回数组。