首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用可怕的事件上传的Node.js文件不会被解雇。

使用可怕的事件上传的Node.js文件不会被解雇。
EN

Stack Overflow用户
提问于 2019-01-18 10:34:52
回答 1查看 1.1K关注 0票数 0

我正在尝试做一个文件上传使用Node.js和强大的模块。

代码语言:javascript
复制
npm install formidable

然后我做了这个,请阅读笔记-在这里,我可以解释每个函数做什么,并描述算法:

代码语言:javascript
复制
// get access to the files that were sent;
// at this time I don't want the files to be uploaded yet;
// in the next function I will validate those files.
function form_parse() {
    form.parse(req, (err, fields, files) => {
      if (err) return req.Cast.error(err);
      if (Object.keys(files).length==0) return req.Cast.badRequest();
      req.files = files;
      return validate_files();
    });
  }

  // I made an object with options to validate against the
  // files. it works and continues to the process_files()
  // function only whether files are verified.
  function validate_files() {
    let limitations = require('../uploads-limitations');
    try {
      limitation = limitations[req.params.resource];
    } catch(err) {
      return req.Cast.error(err);
    }
    let validateFiles = require('../services/validate-files');
    validateFiles(req, limitation, err => {
      if (err) return req.Cast.badRequest(err);
      return process_files();
    });
  }

  // here is the problem - form.on doesn't get fired.
  // This is the time I want to save those files - after
  // fully verified
  function process_files() {
    form.on('file', function(name, file) {
      console.log(`file name: ${file.name}`);
      file.path = path.join(__dirname, '../tmp_uploads/' + file.name);
    });
    form.on('error', err => {
      return req.Cast.error(err);
    });
    form.on('end', () => {
      console.log(`successfully saved`);
      return req.Cast.ok();
    });
  }

  form_parse();

正如您所看到的,正如我所描述的-验证工作,但是当我想要实际保存这些文件时,form.on (事件)不会被触发。

EN

回答 1

Stack Overflow用户

发布于 2019-01-18 10:46:35

是的,因为在流程结束时,在解析和验证之后,您会附加事件侦听器。在开始解析之前,应该先这样做。因为这些事件(文件上、错误上、最后)都是在解析过程中发生的,而不是在解析之后。

代码语言:javascript
复制
 form.on('file',...) // First, attach your listeners
    .on('error', ...)
    .on('end', ...);

form.parse(req) // then start the parsing
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54252147

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档