【问题标题】:Reading file from MongoDB GridFS on Server Side in NodeJS Application在 NodeJS 应用程序的服务器端从 MongoDB GridFS 读取文件
【发布时间】:2019-11-11 11:48:02
【问题描述】:

我想从 MongoDB GridFs 读取文件并将其附加到从节点邮件程序发送的邮件中。所以我需要在服务器端读取这个文件,这意味着我无权访问 http 请求或响应对象,我无法通过管道将读取流传输到互联网上多个地方建议的响应。

我读取文件并作为缓冲区发送的代码如下 -

let _fetchFileById = async (fileId, options) => {
  let db = options.db
    , gfs = Grid(db, mongo)
    , filename = fileId
    , file_buf = new Buffer('buffer');
  return new Promise((resolve,reject) => {
    gfs.collection('jobdescription')

    let readstream = gfs.createReadStream({
      filename: filename
      , root: 'jobdescription'
    })

    readstream.on('data', function (chunk) {
      console.log("writing!!!");
      // file_buf.push(chunk)
      if (!file_buf)
      file_buf = chunk;
      else file_buf = Buffer.concat([file_buf, chunk]);
    });
    readstream.on('end', function () {
      // var buffer = Buffer.concat(file_buf);
      db.close();
      console.log(`returning`)
      // console.log(file_buf)
      resolve(file_buf)
    })
  })
}

当我在节点邮件程序中使用 file_buf 作为附件的输入时,我得到以下错误 -

TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be one of type string or Buffer. Received type object。任何帮助或指示将不胜感激。

【问题讨论】:

    标签: node.js mongodb nodemailer gridfs


    【解决方案1】:

    最后我没有找到一种方法来读取文件并直接从方法中返回它,但是我做了一个小解决方法,从数据库中读取它并将其临时存储在本地目录中,一旦我将它附加到 nodemailer 我打算删除它.我在这里发布方法,以防万一它对某些人有所帮助-

    exports.downloadFile = async (req, fileName) => {
      let db = req.headers.options.db
        , gridfs = Grid(db, mongo)
    
      gridfs.collection('jobdescription')
      if (gridfs) {
        let fsstreamwrite = fs.createWriteStream(
          path.join(process.cwd(), `./app/jobdescriptions/${fileName}`)
        )
        let readstream = gridfs.createReadStream({
          filename: fileName
        })
        readstream.pipe(fsstreamwrite);
        return readstream.on("close", file => {
          console.log("File Read successfully from database");
          return file;
        })
      } else {
        console.log("Sorry No Grid FS Object");
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-06-29
      • 1970-01-01
      • 2012-11-11
      • 2019-03-10
      • 2015-12-21
      • 1970-01-01
      • 2014-02-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多