1

I need help in upload multiple files using node.js upload file reader.

I am using the fs = require('fs'). I have problem in choose two files,only one file only write in upload directory.

This is my backend

var files = req.files.files[0];
for (var i = 0; i < files.length; i++) {    
  file = files[i];
  fs.readFile(files[i].path, function(error, data) {
    // console.log( files[i].path ) ,here displayed two same both
    fs.writeFile(uploadDirectory() + newFileName, data, function(error) {
    });
  });
}

Please help me. what is the problem in my code. Thanks.

2

1 Answer 1

1

You should avoid using files[i] in asynchronous function's callback which is directly written inside of for-loop. the reason why console.log( files[i].path ) displays same thing twice is because when the code is loaded,the for-loop has already done. so you always get the last element of the array.

the easiest way to fix that is making a new scope(function)

for (var i = 0; i < files.length; i++) {    
  readAndWriteFile(files[i]);
}

var readAndWriteFile = function(file){
    fs.readFile(file.path, function(error, data) {
    // console.log( file.path ) displays what you expect.
    fs.writeFile(/* define new file name */, data, function(error) {
    });
  });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.