将收到的 Koajs CSV 文件转换为 array/object

Convert a received Koajs CSV file to array/object

我正在使用 strapi 构建一个 api 并尝试添加一个 import/export 函数。 导出一个就完成了。但是作为 js 的新手,我不确定在实施导入过程时如何处理文件。

这是我从请求中获取文件的方式:

var file = ctx.request.files.file;

这是 console.log(文件)输出:

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 的上下文中写下来。

  1. 在 strapi 中导出一个可以重复用于所有 csv 导入的函数

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. 每当您必须处理 csv 时,导入并重复使用导出的函数

const parseCsv = require('.pathToExportedFunction/parseCsv');

const myCsv = await parseCsv('filePath.csv');

console.log(myCsv);