0

I'm now stuck with my project using NodeJS and Busboy. I'm trying to retrieve all the variables from my router and send it to controllers.

app.js (routes)

router.post('/product', function (req, res) {
var fields = {};
req.busboy.on('field', function(fieldname, val) {
        fields[fieldname] = val;
});
req.busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
    fields[filename] = file;
});
req.pipe(req.busboy);


productController.addNewProduct(fields, function (data) {
    res.json(data);
});
});

ProductController.js

addNewProduct: function (params, callback) {
    productLogic.addNewProduct(params, function (data) {
        callback(data);
    });
},

ProductLogic.js

addNewProduct: function (params, callback) {
    Product.findOne({ name: params.name }, function (err, product) {
        if(err) callback({ status: false, message: err });

        if(product)
            callback({ status: false, message: 'Produk sudah ada.' });

        var newProduct = new Product({
            name: params.name,
            category_id: params.category_id,
            description: params.description,
            is_active: true
        });

        newProduct.save(function (err, result) {
            if(err) callback({ status: false, message: err });

            callback({ status: true, message: result });
        });
    });
},

My goal is to process the data all at once. And now I'm not sure if I can achieve it with busboy.

Please help me on this.

Bunch of thanks in advance

Edwin Yoyada
  • 21
  • 1
  • 4

2 Answers2

0

You should wait for busboy to finish parsing your form before calling your method.

busboy.on('finish', function() {
  productController.addNewProduct(fields, function (data) {
    res.json(data);
  });
});
marton
  • 1,300
  • 8
  • 16
0

I think I already found the answer. Thanks to marton for the heads up.

I've tried:

busboy.on('finish', function() {});

but it never emitted.

The reason is I have to file.resume() in my busboy.on('file'), example:

busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
fields[fieldname] = file;
file.resume();

Once again thanks :)

Edwin Yoyada
  • 21
  • 1
  • 4