在节点js中是否存在类似角度$ watch的内容

时间:2016-04-19 02:06:43

标签: javascript angularjs node.js

我是网络服务的新手,我的知识在节点js中并不那么深,所以如果问题不正确,我会提前道歉。 我的问题是我的angular-node js应用程序中有两个函数。 第一个功能,将文件上传到服务器上的公共文件夹

  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});
    });
});

第二个功能,调用执行java应用程序

  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);
    });
}

在节点js中有类似angular $ watch的东西,我可以在文件上传功能上设置它,所以如果文件已成功上传,则调用java函数

@Paul提供的解决方案(已修改)

  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);
        });
        // In my case java app parsing xls to json around 5-8 sec, that's why I'm using timeout
        setTimeout(10000);
        // then respond to the client so it's not waiting:
        res.json({error_code:0,err_desc:null});
    });
    //return req.child;
});

1 个答案:

答案 0 :(得分:1)

有很多方法可以为此组织代码,但实际上你需要在上传处理程序的回调中调用你的java函数。这样的事情应该有效:

 /** 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});
    });
});