Busboy和GridFS不会将文件保存到文件系统

时间:2015-08-07 04:16:22

标签: javascript node.js

调用以下POST API时,应将文件保存到文件系统。但是,该文件未保存。我可以在控制台中看到该文件,但无法保存/写入该文件。 我有以下代码:

router.post('/notes', function(req, res, next) {
  var gfsstream, startFileWrite, endFileWriteTime;
  var busboy = new Busboy({ headers: req.headers });

  busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
    startFileWrite = new Date().getTime();
    console.log('File [' + fieldname + ']: filename: ' + filename);

    gfsstream = gfs.createWriteStream('/uploads');
    file.on('data', function(data) {
      gfsstream.write(data);
    });
    file.on('end', function() {
      gfsstream.end();
      req.pipe(gfsstream);
    });
    gfsstream.on('close', function (file) {
      // do something with `file`
     endFileWrite = new Date().getTime();
     console.log('File [' + fieldname + '] Finished');
     console.log("Time needed: " + (endFileWrite - startFileWrite) + " ms");
    });
  });

  busboy.on('error', function(err) {
    console.error(err);
    res.sendStatus(500, 'ERROR', err);
  });

  busboy.on('finish', function end() {
    res.sendStatus(200);
  });
  req.pipe(busboy);
});

req.pipe(gfsstream)可能是这里的问题,但我不确定是什么阻止了文件的保存。

1 个答案:

答案 0 :(得分:1)

只需file.pipe(gfsstream)并使用finish事件代替close事件:

busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
  startFileWrite = new Date().getTime();
  console.log('File [' + fieldname + ']: filename: ' + filename);

  gfsstream = gfs.createWriteStream('/uploads');
  file.pipe(gfsstream).on('finish', function() {
    endFileWrite = new Date().getTime();
    console.log('File [' + fieldname + '] Finished');
    console.log("Time needed: " + (endFileWrite - startFileWrite) + " ms");
  });
});