In Node Как скачать файл docx с S3 и разобрать его - PullRequest
0 голосов
/ 04 апреля 2020

У меня есть веб-приложение, которое загружает файлы doc / docx в корзину s3.

Я хочу, чтобы пользователи могли отображать эти файлы как html без загрузки файла. В конечном итоге мне нужно использовать это с Heroku, поэтому я считаю, что мне необходимо временно сохранить файл в памяти.

Я пытаюсь адаптировать решение для файлов xlsx:

Загрузите xlsx из S3 и проанализируйте его

Вот текущий код:

...
const AWS = require('aws-sdk');
const mammoth = require('mammoth');

async function downloadFile(target){
  AWS.config.update({
    accessKeyId: process.env.AWS_ACCESS_KEY_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  });

  const s3 = new AWS.S3();
  const stream = await s3.getObject(
    { 
      Bucket: process.env.AWS_BUCKET, 
      Key: target.file_url.split("com/").reverse()[0]
    }).createReadStream();
  console.log('this is the stream: ',stream)
  return stream;
}

router.put('/:id/download', async (req, res, next) => {
  console.log('hitting download route')

  var id = req.params.id;
  let upload = await Upload.query().findById( id ).eager('user');

  console.log("file to download is: ", upload.name)

  var s3FileObject = downloadFile(upload)

  console.log('this is the downloaded file: ', s3FileObject)
  res.send (s3FileObject)

  // mammoth code commented until we successfully download the object
  // mammoth.convertToHtml({ path: '/Users/dariusgoore/Downloads/1585930968750.docx' })
  //   .then(async function(result) {
  //     await Upload.query().findById( id )
  //       .patch({
  //          html: result.value,
  //          conversion_messages: result.messages
  //       })  
  //     res.json(result);
  //   })

    // .done();
});

консоль возвращает следующее:

hitting download route
file to download is:  COVID-19.docx
this is the downloaded file:  Promise { <pending> }
this is the stream:  PassThrough {
  _readableState:
   ReadableState {
     objectMode: false,
     highWaterMark: 16384,
     buffer: BufferList { head: null, tail: null, length: 0 },
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: null,
     ended: false,
     endEmitted: false,
     reading: false,
     sync: false,
     needReadable: true,
     emittedReadable: false,
     readableListening: false,
     resumeScheduled: false,
     emitClose: true,
     destroyed: false,
     defaultEncoding: 'utf8',
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },
  readable: true,
  domain: null,
  _events:
   [Object: null prototype] { prefinish: [Function: prefinish] },
  _eventsCount: 1,
  _maxListeners: undefined,
  _writableState:
   WritableState {
     objectMode: false,
     highWaterMark: 16384,
     finalCalled: false,
     needDrain: false,
     ending: false,
     ended: false,
     finished: false,
     destroyed: false,
     decodeStrings: true,
     defaultEncoding: 'utf8',
     length: 0,
     writing: false,
     corked: 0,
     sync: true,
     bufferProcessing: false,
     onwrite: [Function: bound onwrite],
     writecb: null,
     writelen: 0,
     bufferedRequest: null,
     lastBufferedRequest: null,
     pendingcb: 0,
     prefinished: false,
     errorEmitted: false,
     emitClose: true,
     bufferedRequestCount: 0,
     corkedRequestsFree:
      { next: null,
        entry: null,
        finish: [Function: bound onCorkedFinish] } },
  writable: true,
  allowHalfOpen: true,
  _transformState:
   { afterTransform: [Function: bound afterTransform],
     needTransform: false,
     transforming: false,
     writecb: null,
     writechunk: null,
     writeencoding: null } }

Где такое файловый объект?

...