尝试在csv上写单独的行

时间:2019-03-11 15:19:35

标签: javascript loops csv

我从csv文件中的数据列表运行API调用。然后,我返回结果并将其写回到新的csv文件。我遇到的问题是它将结果写回到一行。循环完成后,是否有npm软件包或一种将结果写回到单独的行中的方法?下面是我正在运行的代码。

    /*AXIOS GET API CALL URL */
    axios.get(url+'term='+orgName +'&location='+city + state + zipCode,{
        headers: {
            Authorization: 'Bearer ' + token
        }
    })
    /*If results are less than 1, moves on to fetchWhitePages API, ELSE, passes in the data*/
        .then(res => {
            if(Array.isArray(res.data.businesses) && res.data.businesses.length === 0){
               return fetchWhitePages(data);

            }else{
                console.log('RUNNING YELPAPI');
                /*For loop to get JSON objects within YelpAPI */

                for(let i =0; i < res.data.businesses.length; i++ ){

                    churchListing.push('Name: ' + res.data.businesses[i].name);
                    churchListing.push('Address: ' + res.data.businesses[i].location.address1);
                    churchListing.push('City: ' + res.data.businesses[i].location.city);
                    churchListing.push('Zip: ' + res.data.businesses[i].location.zip_code);
                    churchListing.push('Phone: ' + res.data.businesses[i].phone + "/n");
                    // console.log(churchListing);

                   fs.writeFile('my.csv', churchListing,  (err) => {
                       if(err) throw err;
                   });

                }

            }
        })
        .catch(err => {
            console.log(err)
        })
}

1 个答案:

答案 0 :(得分:0)

如果您考虑自己构建字符串,则不需要插件。以下代码将CSV的第一行写为标题,然后将每行追加为CSV数据:

const businesses = [
{name:'one', address: 'one address', city: 'one city', zip: '111111', phone: '1111111111'},
{name:'two', address: 'two address', city: 'two city', zip: '222222', phone: '2222222222'},
{name:'three', address: 'three address', city: 'three city', zip: '333333', phone: '33333333'},
]

//Header
let churchListingCSV = "Name, Address, City, Zip, Phone\n";
//Data rows
businesses.forEach(row => {
  churchListingCSV += row.name+',';
  churchListingCSV += row.address+',';
  churchListingCSV += row.city+',';
  churchListingCSV += row.zip+',';
  churchListingCSV += row.phone;
  churchListingCSV += "\n";
});

console.log(churchListingCSV);
/*
fs.writeFile('my.csv', churchListingCSV, (err) => {
  if (err) throw err;
});
*/

此解决方案假定“行定界符”是换行符,“字段定界符”是逗号(传统CSV格式)。