Assigned global variable issue in nodejs

I am trying to upload file in node server.

I am defining uploadedfileName as a global variable. After I am uploading the file at that time I am trying to store file name in to this variable I want to get the global variable in getResponseWithPython function with the file name

HTML:

<form id="upload" action="/upload" method="POST" enctype="multipart/form-data">
   <input type="submit" />
</form>

I am defining uploadedfileName as a global variable

JS:

** //declartion**
global.uploadedFileName = '';

//upload route
app.post('/upload', function(req, res) {

    var busboy = new Busboy({
        headers: req.headers
    });
    busboy.on('file', function(fieldname, file, filename, encoding, mimetype) {
        console.log("Context path=" + __dirname);
        var saveTo = path.join(__dirname + "/uploads", filename);

        console.log('Uploading: ' + saveTo);
        file.pipe(fs.createWriteStream(saveTo));

        ** //After I am uploading the file at that time I am trying to store file name in to this variable**
        global.uploadedFileName = filename;

    });
    busboy.on('finish', function() {
        console.log('Upload complete');
        res.writeHead(200, {
            'Connection': 'close'
        });
        res.end("That's all folks!");
    });

    return req.pipe(busboy);

});


function getResponseWithPython(prevMsg, cb) {

    ** // I want to get the global variable in this function with the file name**
    console.log(" global.uploadedFileName::: " + global.uploadedFileName);
    var pythonRes = '';
    var formData = {

        // Pass data via Streams
        input_file: fs.createReadStream(__dirname + '/GoogleHeader.csv')

    };
    process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";
    var req = request.post({
        url: 'https://google.com:443/classification/',
        formData: formData
    }, function optionalCallback(err, httpResponse, body) {
        if (err) {
            return console.error('upload failed:', err);
        }
        console.log('Upload successful!  Server responded with:', body);
        pythonRes = body;

        return cb(pythonRes);
    });

};

Note: I have mentioned comments in the code to understand flow of code and my requirement

1 answer

  • answered 2018-05-16 05:56 Minar Mnr

    Do not assign value during declaration.

    **//declartion**
    global.uploadedFileName;