Nb_me Nb_me - 14 days ago 5
Javascript Question

write array to file after looping node js

I have yet to find a answer to my problem with the examples from questions others have asked on this.
I wrote a little web scraper that stores data to 1 array and would like to write it (the arrays) to a file. I'm having trouble setting things up correctly.

I am using nodejs. Could someone write a sample that takes an array content then writes to a file. please break it down to basic, I am still new at programming.

Thanks the code is below

var content = [];
var request = require('request');
var cheerio = require('cheerio');
var URL = 'http://www.amazon.com';



request(URL, function(error, response, html){

if (error){

consol.log('Error:', error);
}
if (response.statusCode !== 200) {

console.log('Invalid Status Code Returned:', response.statusCode);
}

//console.log(html);
var $ = cheerio.load(html);


$('td').each(function (i, element) {


var a = $(this).next();
var trimmed_a = a.text();

trimmed_a = trimmed_a.trim();
var str = trimmed_a.replace(/\s\s+/g,"");
var newStr = str.trim();

content.push(newStr);



});

console.log(content);


})

Answer

Simplest possible answer:

var fs = require('fs');
var arr = ['cat','dog','bird'];
var filename = 'output.txt';
var str = JSON.stringify(arr, null, 4);

fs.writeFile(filename, str, function(err){
    if(err) {
        console.log(err)
    } else {
        console.log('File written!');
    }
});

Here, arr, would be your array of data, that your casting to a string because fs.writeFile expects a string. I used the null,4 additional arguments to make it pretty print so you can see it with a four space indent.

Hope this helps!

Comments