Anton Anton - 7 months ago 17
Javascript Question

Is there something like angular $watch in node js

I'm rookie in Web services and my knowledges are not so deep in node js, so I apologize in advance if the question is not correct.
My Question is I have two functions in my angular-node js app.
First function, uploading file to public folder on server

var storage = multer.diskStorage({ //multers disk storage settings
destination: function (req, file, cb) {
cb(null, './demo/');
},
filename: function (req, file, cb) {
//var datetimestamp = Date.now();
cb(null, file.originalname
//file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1]
);
}
});
var upload = multer({ //multer settings
storage: storage
}).single('file');
/** API path that will upload the files */
app.post('/upload', function(req, res) {
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
return;
}
res.json({error_code:0,err_desc:null});
});
});


Second funciton, calling executive java app

var child = function() {
spawn('java', ['-Xms64M', '-Xms64M', '-jar', '/home/ubuntu/code/ParseExcel.jar',
'/var/www/html/demo/test.xls']);
child.on('close', function (exitCode) {
if (exitCode !== 0) {
console.error('Something went wrong!');
}
});
child.stderr.on('data', function (data) {
process.stderr.write(data);
});
}


Is there something like angular $watch in node js that I could set it on file upload function, so if the file has been successfully upload call java function

Solution provided by @Paul (modified)

app.post('/upload', function(req, res) {
upload(req,res,function(err){
if(err){
res.json({error_code:1,err_desc:err});
return;
}
// first, call your child code:
var child = spawn('java', ['-Xms64M', '-Xms64M', '-jar', '/home/ubuntu/code/ParseExcel.jar',
'/var/www/html/demo/test.xls']);
child.on('close', function (exitCode) {
if (exitCode !== 0) {
console.error('Something went wrong!');
}
});
child.stderr.on('data', function (data) {
process.stderr.write(data);
});
// then respond to the client so it's not waiting:
res.json({error_code:0,err_desc:null});
});
//return req.child;
});

Answer

There're a lot of ways to organize your code for this, but essentially you need to call your java function inside the callback for your upload handler. Something like this should work:

 /** API path that will upload the files */
app.post('/upload', function(req, res) {
    upload(req,res,function(err){
        if(err){
            res.json({error_code:1,err_desc:err});
            return;
        }
        // first, call your child code:
        child();
        // then respond to the client so it's not waiting:
        res.json({error_code:0,err_desc:null});
    });
});