从CSV文件读取到JSON将返回一个空数组

时间:2017-05-06 22:40:12

标签: javascript json node.js csv

所以我有这个函数将json对象打印成字符串:

GetAllArticles: (req, res) => {
        var allArticles = getAllArticles();

        res.setHeader("Content-Type", 'application/json');
        res.write(JSON.stringify(allArticles));  //cast object to string

        res.end();
}

这是我的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;
}

文章:

function Article(articleName, quantity, price) {
    this.articleName = articleName;
    this.quantity = quantity;
    this.price = price;
}

网页上的输出是:[] 所以我检查了加载的jsonObject是否在数组中并且它们是,但在我将它们转换为字符串之后输出只是“[]”..

1 个答案:

答案 0 :(得分:0)

这是异步代码的经典现金

您需要更改getAllArticles

function getAllArticles() {
    return new Promise((resolve) => {
        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) => {
                     resolve(result);
                })

        });
    })
}

并为你的路线

GetAllArticles: (req, res) => {
    getAllArticles().then((result) => {
        res.setHeader("Content-Type", 'application/json');
        res.write(JSON.stringify(result));  //cast object to string
        res.end();
    });  
}