[英]Convert a received Koajs CSV file to array/object
我正在使用 Strapi 構建一個 api 並嘗試添加一個導入/導出功能。 導出完成。 但是由於我是 js 新手,我不確定在實現導入過程時如何處理文件。
這就是我從請求中獲取文件的方式:
var file = ctx.request.files.file;
這是 console.log(file) 輸出:
File {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
size: 127,
path: '/tmp/upload_3f202079094c364546a9d4a792a1d5f5',
name: 'declaracion.csv',
type: 'text/csv',
hash: null,
lastModifiedDate: 2020-10-30T11:37:37.093Z,
_writeStream: WriteStream {
_writableState: WritableState {
objectMode: false,
highWaterMark: 16384,
finalCalled: true,
needDrain: false,
ending: true,
ended: true,
finished: true,
destroyed: true,
decodeStrings: true,
defaultEncoding: 'utf8',
length: 0,
writing: false,
corked: 0,
sync: false,
bufferProcessing: false,
onwrite: [Function: bound onwrite],
writecb: null,
writelen: 0,
afterWriteTickInfo: null,
bufferedRequest: null,
lastBufferedRequest: null,
pendingcb: 0,
prefinished: true,
errorEmitted: false,
emitClose: false,
autoDestroy: false,
bufferedRequestCount: 0,
corkedRequestsFree: [Object]
},
writable: false,
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: undefined,
path: '/tmp/upload_3f202079094c364546a9d4a792a1d5f5',
fd: null,
flags: 'w',
mode: 438,
start: undefined,
autoClose: true,
pos: undefined,
bytesWritten: 127,
closed: true,
[Symbol(kCapture)]: false,
[Symbol(kIsPerformingIO)]: false
},
[Symbol(kCapture)]: false
}
任何想法將文件轉換為數組或對象?
您可以使用csv-parser來實現這一點,他們的文檔具有足夠的描述性,但我會在 Strapi 的上下文中將其寫下來。
const fs = require('fs'); const csv = require('csv-parser'); function parseCsv(filePath) { const results = []; return new Promise(resolve => { fs.createReadStream(filePath) .pipe(csv()) .on('data', data => results.push(data)) .on('end', () => { resolve(results); }); }); } module.exports = parseCsv;
const parseCsv = require('.pathToExportedFunction/parseCsv'); const myCsv = await parseCsv('filePath.csv'); console.log(myCsv);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.