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.
-
is it giving some error?Mritunjay– Mritunjay2014年07月31日 15:22:20 +00:00Commented 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.Kiksy– Kiksy2014年07月31日 15:23:13 +00:00Commented Jul 31, 2014 at 15:23
-
What if you log in the foreach-callback? Have you tried file['date']?Hank Lapidez– Hank Lapidez2014年07月31日 15:23:31 +00:00Commented Jul 31, 2014 at 15:23
3 Answers 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);
answered Jul 31, 2014 at 15:24
Eugene Obrezkov
2,9962 gold badges19 silver badges35 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
answered Jul 31, 2014 at 15:28
mike
5,2312 gold badges29 silver badges32 bronze badges
Comments
lang-js