在需要路径或 link 时将 pdf 文件传递​​给函数

Passing a pdf file to a function when it requires a path or link

我正在为在线图书馆开发 Web 应用程序。我想从将要上传的 PDF 中提取元数据,为此我使用 nodejs 库 pdf.js-extract 和 multer-gridfs-storage 进行上传。问题是我收到一个 PDF 文件 (req.file),该函数需要 PDF 文件的路径或 link,因此显示错误

"TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be one of type string, Buffer, or URL. Received type object"

我想知道是否有办法将文件作为 link 传递,将文件临时保存在本地或找到另一个符合我需要的库。

这是我当前的代码。

const PDFExtract  = require('pdf.js-extract').PDFExtract;

app.post('/upload', upload.single('file'), (req, res) => {
  const pdfExtract = new PDFExtract();
  const options = {};

  pdfExtract.extract(req.file, options, (err, data) => {
      if (err){
        res.status(404).send({ message: err });
      }
      res.status(200).send({ message: data });
  });
});

(编辑澄清)我正在使用带有 gridFS 的 multer 将文件上传到 mongoose。

const multer = require('multer');
const GridFsStorage = require('multer-gridfs-storage');

// Create storage engine
const storage = new GridFsStorage({
  url: mongoURI,
  file: (req, file) => {
    return new Promise((resolve, reject) => {
      crypto.randomBytes(16, (err, buf) => {
        if (err) {
          return reject(err);
        }
        const filename = buf.toString('hex') + path.extname(file.originalname);
        const fileInfo = {
          filename: filename,
          bucketName: 'uploads'
        };
        resolve(fileInfo);
      });
    });
  }
});
const upload = multer({ storage });

解决方案灵感来自 Oliver Nybo

app.post('/upload', upload.single('file'), (req, res) => {
  const pdfExtract = new PDFExtract();
  const options = {};

  var readableStream = gfs.createReadStream({ filename : req.file.filename });
  var buff;

  var bufferArray = [];
  readableStream.on('data',function(chunk){  
      bufferArray.push(chunk);
  });
  readableStream.on('end',function(){
      var buffer = Buffer.concat(bufferArray);
      buff=buffer;
      pdfExtract.extractBuffer(buff, options, (err, data) => {
        if (err) {
          res.status(404).send({ message: err });
        }
        res.status(200).send({ message: data });
      });
  })
});

根据multer's api documentation,可以使用req.file.path获取上传文件的完整路径

const PDFExtract  = require('pdf.js-extract').PDFExtract;

app.post('/upload', upload.single('file'), (req, res) => {
  const pdfExtract = new PDFExtract();
  const options = {};

  pdfExtract.extract(req.file.path, options, (err, data) => {
      if (err){
        res.status(404).send({ message: err });
      }
      res.status(200).send({ message: data });
  });
});

编辑: 我刚刚阅读了 multer options 并且有一个名为 preservePath.

的选项

preservePath - Keep the full path of files instead of just the base name

编辑 2: 我认为您需要使用 gridfs-stream, then convert it into a buffer (like in this thread), and then use PDFExtract's extractBuffer 函数从数据库中提取文件。