0

I am trying to delete array of files but one or two of them gets deleted .Pls check the code I am sure I am doing something wrong. I am searching for a file in directory and if found I am First Removing it from db..and after response I am removing file from directory

if (files.length > 0) { files.forEach(function(filename) { fileDir = path.join(__dirname, '/uploads/' + decodeURI(filename)); fs.stat(fileDir, function(err, stats) { if (stats.isFile()) { // fs.unlink(fileDir, function(err) { form_op.deleteImg(url.resolve('http://localhost/uploads/', filename), query._id, function(err, result) { if (err) { throw console.log(err) } fs.unlink(fileDir); }); // }); } }); done++; }); 

through debugging I found that filename and fileDir variable are getting next file in the array without waiting for fs.stat(fileDir, function(err, stats) { to complete.. is there any other way I can do it? the check and remove?? my files variable is array only file's name.

1 Answer 1

2

fileDir = path.join(__dirname, '/uploads/' + decodeURI(filename));

You are missing a var declaration here, therefore the fileDir variable is global and shared by all of your callbacks.

Use var fileDir = ... to have the variable scoped to your function.

Sign up to request clarification or add additional context in comments.

1 Comment

np, it's a pretty common trap. strict mode can be helpful to prevent it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.