Thursday, 16 March 2017

readFileAfterClose getting called before function execution is completed. For Reading file content after upload

Posting File Content from HTML form to server. Before parseData(data) function execution is completed, res.end() or res.redirect("back") is called. How can I execute parseData(data) function before the execution ends.

app.route('/upload')
    .post(function (req, res, next) {
        var fstream;
        req.pipe(req.busboy);
        req.busboy.on('file', function (fieldname, file, filename) {
            console.log("Uploading: " + filename);

            //Path where files will be uploaded
            fstream = fs.createWriteStream(__dirname + '/uploads/' + filename);

            file.pipe(fstream); 

            fs.readFile(__dirname + '/uploads/' + filename, 'utf8', function(err,data){
                if (err) throw err;

                **parseData(data);**
            })

            fstream.on('close', function () {                      
                console.log("Upload Finished of " + filename); 
                **res.redirect("back");**
            });

        });
});

function parseData(string){
       splittedStringArray.forEach(function (log) {
          var reverseLog = log.split(' ').reverse();
          // Trying to do something 
       });
}


TypeError: Cannot read property 'split' of undefined
    at C:\Users\ayush\Desktop\faasos\server.js:50:51
    at Array.forEach (native)
    at parseData (C:\Users\ayush\Desktop\faasos\server.js:48:25)
    at C:\Users\ayush\Desktop\faasos\server.js:30:17
    at tryToString (fs.js:455:3)
    at FSReqWrap.readFileAfterClose [as oncomplete] (fs.js:442:12)



via Ayush

No comments:

Post a Comment