node.jsasynchronousexpressfilesystemslpr

sequentially run functions in nodejs


I'm very new to node and have run into issues with running some functions sequentially and the use of callbacks. I have tried to use the async module, but, I think I'm missing something because it does my functions out of order.

In the most simplest terms I would like to retrieve some data in the form of url params and then: 1. write them to a file 2. lpr print them 3. delete the file

My current code deletes the file before printing.ie step 3 before step 2.Would anyone offer some advice on how best to perform these in order? Thanks in advance.

router.get('/zplprint/:barcode/:zpl', function(req, res) {
var zpl = req.params.zpl;
var filename  = appDir + "/uploads/" + req.params.barcode + ".zpl";
console.log(req.params.zpl);
res.send("received zpl: " + req.params.zpl);

async.series([
    function(callback){
        fs.writeFile(filename, zpl, function(err) {
        if(err) {
            callback(err);
            return;
        }
        console.log("The file was saved! to "+filename);
            callback();
        });
    },
    function(callback){
        CupsPrinterName = nconf.get('Print:PrinterName');
        console.log(CupsPrinterName);
        var cmd = 'lpr -P ' + CupsPrinterName + ' -o raw ' + filename;
        exec(cmd, function(error, stdout, stderr) {
            // command output is in stdout'
            console.log(cmd);
            console.log("file printed");
        });
        callback();
    },
    function(callback){
        fs.unlink(filename, function (err) {
            console.log('   deleting ' + filename);

        });
        callback();
    }
]);

});


Solution

  • You are calling the callback() function at the same level of exec(), exec is asynchronous and will log "file printed" after deleting the file because callback() was called outside of exec() and not when the function ends. Try calling callback after printing:

    function(callback){
        CupsPrinterName = nconf.get('Print:PrinterName');
        console.log(CupsPrinterName);
        var cmd = 'lpr -P ' + CupsPrinterName + ' -o raw ' + filename;
        exec(cmd, function(error, stdout, stderr) {
            // command output is in stdout'
            console.log(cmd);
            console.log("file printed");
            callback();
        });        
    },