I wrote the following code to create a formatted JSON file that holds all names of files (testfile1, testfile2, testfile3) that exist in a directory called "uploads".
const fs = require("fs");
let toJson = {files: []};
let file = new Object();
function createJSON(){
fs.readdir("./uploads", (err, files) => {
//add each files name to obj
files.forEach((item, index) => {
  file.name = item;
  console.log(index, item);
  toJson.files.push(file);
});
var saveJson = JSON.stringify(toJson, null, 4);
fs.writeFile('./files.json', saveJson, 'utf8', (err) => {
  if(err) throw err;
  console.log(err);
});
});
}
The output from console.log(item, index) is as expected:
0 testfile1
1 testfile2
2 testfile3
However, the JSON file that is being created holds the following names:
{
"files": [
    {
        "name": "testfile3"
    },
    {
        "name": "testfile3"
    },
    {
        "name": "testfile3"
    }
]
}
instead of the intended
{
"files": [
    {
        "name": "testfile1"
    },
    {
        "name": "testfile2"
    },
    {
        "name": "testfile3"
    }
]
}
 
     
     
    