0

I'm getting an array of files, and then I want to add the date and size properties to each of those file objects, but using the code below, they don't get added. I know that's my fs.statSync(p + file).mtime.getTime() and fs.statSync(p + file).size have values in them.

var files = fs.readdirSync(p);

files.sort(function(a, b) {
           return fs.statSync(p + a).mtime.getTime() - 
                  fs.statSync(p + b).mtime.getTime();
});

files.forEach(function(file) {
    file.date = fs.statSync(p + file).mtime.getTime();
    file.size = fs.statSync(p + file).size;
});

console.log('files::'+files); // doesn' have the new file.date and file.size property.
3
  • is it giving some error? Commented Jul 31, 2014 at 15:22
  • no its just not adding the new properties. The array stays in the same form as when it started. Commented Jul 31, 2014 at 15:23
  • What if you log in the foreach-callback? Have you tried file['date']? Commented Jul 31, 2014 at 15:23

3 Answers 3

3

When you writing value into file variable it's not saving because file it's variable that lives into local scope. So a quick solution for this:

var files = fs.readdirSync(p),
    result = [];

files.sort(function(a, b) {
           return fs.statSync(p + a).mtime.getTime() - 
                  fs.statSync(p + b).mtime.getTime();
});

files.forEach(function(file) {
    file.date = fs.statSync(p + file).mtime.getTime();
    file.size = fs.statSync(p + file).size;
    result.push(file);
});

console.log('files::' + result);
Sign up to request clarification or add additional context in comments.

Comments

0

Similar to Eugene's answer, but this uses map:

files = files.map(function(file) {
  file.date = fs.statSync(p + file).mtime.getTime();
  file.size = fs.statSync(p + file).size;
  return file;
});

DEMO

Comments

0

The file variable is a local variable. Without having to create a new array as Eugene did, you can update the original array in this way:

var files = fs.readdirSync(p);

files.sort(function(a, b) {
           return fs.statSync(p + a).mtime.getTime() - 
                  fs.statSync(p + b).mtime.getTime();
});

files.forEach(function(file, index, array) {
    array[index].date = fs.statSync(p + file).mtime.getTime();
    array[index].size = fs.statSync(p + file).size;
});

console.log('files::'+files);

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.