Friday, 17 March 2017

Array value is null outside of function [duplicate]

I am new in nodejs. I have written the following code.

var sampleFile = [];
  var fileArray = [];
  var newFileName = '';
  sampleFile = req.files.sampleFile;
  for (var i = 0; i < sampleFile.length; i++) {
    // console.log(sampleFile[i].name);
    var reqFile = sampleFile[i].name;
    var rand = ~~(Math.random() * 256)
    newFileName = day+rand+'.jpg';

    sampleFile[i].mv(path+newFileName, function(err) {
        if (err){
            return res.status(500).send(err);
        } else{
        var query = connection.query('INSERT INTO `files`(`file_name`, `path`) VALUES ("'+newFileName+'","'+path+'")', function(err, result) {
            });
        fileArray.push(newFileName);
        console.log('fileArray='+fileArray);
        }
    });
  }
  console.log('fileArray='+fileArray);

Here the problem is fileArray is null outside the function.But fileArray has value inside the function. I have tried using fileArray as global but still it does not get the value outside the function. How to get it?

console.log

fileArray=
output.zip written.
fileArray=2017-03-17_6-17-38190.jpg
fileArray=2017-03-17_6-17-38190.jpg,2017-03-17_6-17-38190.jpg



via Dipankar Naskar

No comments:

Post a Comment