M
M
Maxim Supreme2018-03-14 14:31:16
JavaScript
Maxim Supreme, 2018-03-14 14:31:16

How to save array to csv file?

There is such a code that parses data from the site and writes it as an array.
Question: how to save an array in a csv file at the root of the project (help me finish the code)?

const tress = require('tress');
const needle = require("needle");
const cheerio = require("cheerio");
const async = require("async");
const fs = require('fs');

let aUrl = [
    'ссылка на товар',
    'ссылка на товар',
    'ссылка на товар',
];

const jquery = body => cheerio.load(body);

let products = [];

let parsePage = ($) => {
    let name = $("#shop-production-view > h1").first().text();
    let categories = $(".breadcrumb").text();
    let price = $(".price").text();
    let content = $('.content_item').html();
    let images = $(".image").find("img").attr("src");

    // let $imageLink = $(".shop-production-view .image a"),
    //     img = '';
    // if ($imageLink.length > 0) {
    //     img = $imageLink.attr("href");
    // }


    products.push({
        name,
        categories,
        content,
        price,
        images,
        // img,
    });
};

let q = tress((url, callback) => {
    needle.get(url, {  }, (err, res) => {
        if (err) {
            throw err;
        }

        parsePage(jquery(res.body));

        callback();
    });
}, 5);

q.drain = () => {
    console.log(products);
};

for (let i = 0; i < aUrl.length; i++) {
    q.push(aUrl[i]);
}

Answer the question

In order to leave comments, you need to log in

3 answer(s)
M
Maxim Supreme, 2018-03-14
@MSupreme

Instead of this piece of code

q.drain = () => {
    console.log(products);
};

Now this is a piece of code:
fs.writeFile('data.json', JSON.stringify(products), (err) => {
        if (err) throw err;

        console.log("saved");
    });

JSON.stringify(products) that's what needed to be inserted to make it work as it should)))

C
coderisimo, 2018-03-14
@coderisimo

example .

var rows = ;
var csvContent = "data:text/csv;charset=utf-8,";
rows.forEach(function(rowArray){
   let row = rowArray.join(",");
   csvContent += row + "\r\n";
}); 
//затем через  window.open 

var encodedUri = encodeURI(csvContent);
window.open(encodedUri);

E
evilray, 2018-03-14
@evilray

csv.adaltas.com/stringify
Examples are on github

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question