【发布时间】:2021-11-01 05:01:05
【问题描述】:
我正在遍历一个 CSV 文件 shipmentId.csv,看起来该函数正在读取每一行,但我正在写入的 JSON 文件没有附加。它只是写最后一个 API 响应。如何附加 JSON 文件以保存整个 API 响应循环?
// read csv file
const filePath = path.join(__dirname, 'shipmentId.csv');
fs.readFile(filePath, async (error, data) => {
if (error) {
return console.log('error reading file');
}
// parsedData = [{id, ShipmentId, ...}, {id, ...}, ...]
const parsedData = await neatCsv(data);
parsedData.map((rowObj) => {
// rowObj = {id, ShipmentId, ...}
let id = rowObj.ShipmentId;
// console.log(id)
(async function () {
const mwsRequestData = {
Version: '2010-10-01',
Action: 'ListInboundShipmentItems',
SellerId: config.SellerId,
MWSAuthToken: config.MWSAuthToken,
ShipmentId: id,
};
try {
let response = await mws.fulfillmentInboundShipment.search(mwsRequestData);
if (response.status == 200) {
throw new Error(`Unexpected status code ${response.status}, expected 200`);
}
console.log('response', response);
// let data = JSON.stringify(response, null, 2);
fs.writeFileSync('todo2.json', JSON.stringify(response, null, 2));
} catch (err) {
console.log('That did not go well.')
}
}());
});
});
【问题讨论】:
-
这里有多个问题:1)
.map()不支持异步,因此它不会序列化回调内的异步操作 - 使用for循环代替更高级别的 @ 987654325@ 函数,然后您可以使用await序列化异步操作。 2)fs.readFileSync()替换整个文件内容,因此您不会追加数据,而是用最后的数据覆盖,因此您需要追加或累积所有数据并在完成后一次写入。
标签: node.js csv amazon-mws