So I have this function which prints out json object as strings:
GetAllArticles: (req, res) => {
var allArticles = getAllArticles();
res.setHeader("Content-Type", 'application/json');
res.write(JSON.stringify(allArticles)); //cast object to string
res.end();
}
Here is my getAllArticles:
function getAllArticles() {
var result = [];
result.push(new Article('Gummistiefel', 100, 34.99));
result.push(new Article('Regenmantel', 10, 124.99));
result.push(new Article('HTML5 Buch', 25, 4.99));
//creates a test file
var json2csv = require('json2csv');
var fs = require('fs');
var fields = ["articleName", "quantity","price"];
var csv2 = json2csv({ data: result, fields: fields });
fs.writeFile('file.csv', csv2, function (err) {
if (err) throw err;
console.log('file saved');
});
result = [];//clear the array to save new articles
//load file
const csvFilePath = 'file.csv'
const csv = require('csvtojson')
csv()
.fromFile(csvFilePath)
.on('json', (jsonObj) => {
result.push(jsonObj);
})
.on('done', (error) => {
console.log('end');
})
return result;
}
Article:
function Article(articleName, quantity, price) {
this.articleName = articleName;
this.quantity = quantity;
this.price = price;
}
And the output on the webpage is: [] So I checked if the loaded jsonObject were in the array and they were, but after I convert them to string the output is just "[]"..
via KeyNavas
No comments:
Post a Comment