简体   繁体   中英

Convert a received Koajs CSV file to array/object

I'm using strapi to build an api and trying to add an import/export function. The export one is done. But as Im new with js, am not sure how to handle the file when implementing the import process.

This is how I get the file from request:

var file = ctx.request.files.file;

This is the console.log(file) output:

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
}

Any idea to convert the file to an array or object?

You can use csv-parser to accomplish that, their docs are descriptive enough, but I'll write it down in the context of strapi.

  1. Export a function in strapi that you can reuse for all csv imports

 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;

  1. Import and reuse your exported function whenever you have to deal with csv

 const parseCsv = require('.pathToExportedFunction/parseCsv'); const myCsv = await parseCsv('filePath.csv'); console.log(myCsv);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM