I send an array of values to my node server to be written to a log file.
My $.ajax post works at the client side. At the back-end, I print the array to the console, but when I try to write it to the file using the code below, i get a blank output in the log file.
function log(req,res)
{
var list = req.body;
console.log(list);
for(var i = 0; i < req.body.length; i++)
fs.writeFileSync("./log.dat", JSON.stringify(list[i]) + "\r\n");
}
The array is a collection of JSON objects like this on the console.
Side Note: I can write to the file if I remove JSON.stringify and [i] though.
Any idea what I'm doing wrong?
Edit:
I did this and I get "undefined" in my log file.
try {
for(var i = 0; i < 3; i++)
fs.writeFileSync("./log.dat", list[i] + "\r\n");
} catch (err) {
console.log('Error writing Metadata.json:' + err.message)
}
I've deduced it's something to do with the loop and the array. I can't reference the array by index.
My ajax req code:
var items = {logs: foghorn_items};
path = server + "Foghorn/log";
$.ajax({
url: path,
method: 'POST',
dataType: 'JSON',
data: items,
success: function (data){
alert('Logs sent to file');
}
);
UPDATE
For some reason the loop doesn't work with list.length and req.body.length.