0

Let me preface that I'm a total js noob, so thank you for your help.

I am using the randomuser.me api to create a list of users. However, it only gives me the names in lowercase. So I used this script (with the help of someone else) to capitalize the names. Now I want to take that new data and create a json file. From what I've read, I need to use node.js, but have no idea how to run it properly. I've done npm install and installed this module: https://github.com/jprichardson/node-jsonfile

I'm also using firebase to put the data into a database and hosting it.

//init firebasejs
var config = {
    apiKey: "AIzaSyD0F_1-ynUdzpEkQADrs6BbXUInFCkpBdM",
    authDomain: "random-users.firebaseapp.com",
    databaseURL: "https://random-users.firebaseio.com",
    projectId: "random-users",
    storageBucket: "random-users.appspot.com",
    messagingSenderId: "675456550116"
};
firebase.initializeApp(config);

var database = firebase.database();

var fs = require('fs');

var jsonfile = require('jsonfile')
var file = '/tmp/data.json'

//fuunction to capitalize strings
function capitalize(text) {
    return (!text || !text.length) ?
        text :
        (text[0].toUpperCase() + text.slice(1));
}


$.get("https://randomuser.me/api/ results=20&nat=us&inc=name,gender,picture&format=pretty",
    function(data) {
        if (!data || !data.results)
            return;

        //going through 'data' and capitalizing name and gender
        data.results.forEach(function(user) {
            if (user.name) {
                for (var name in user.name) {
                    user.name[name] = capitalize(user.name[name]);
                }
            }
            if (user.gender) {
                user.gender = capitalize(user.gender);
            }
        });

        console.log(data);

        //write new data to firebase
        database.ref().set(data);

        //write json file?
        var result = JSON.stringify(data, null, 4);
        $('#randomUsers').html(result);

        jsonfile.writeFile(file, data, {spaces: 2}, function(err) {
            console.error(err)
        })


        // var fs = require("fs");
        // fs.writeFile("randomUsers.json", result, function(err) {
        //     if (err) {
        //         return console.log(err);
        //     } else {
        //         console.log("The file was saved!");
        //     }
        // });

  });

Can you js wizards point me in the right direction? Thank you!

aalok89
  • 171
  • 5
  • 14
  • What result are you getting? Firebase is totally irrelevant to the question asked, you should isolate a minimal use case that does not involve firebase queries and get requests. – skylize Jan 15 '18 at 21:46
  • @skylize So I'm confused on how to actually run the script locally from my machine (im using MAMP right now). From my understanding, node doesn't run from the browser. and I was looking at examples that said to use Terminal to do 'node script.js'. Thanks, wasn't sure, so I just included the firebase info just in case. This is what I get when I run 'node script.js' with all firebase references commented out: https://screencast.com/t/kefKKgiV I guess it's not liking the combination of node.js and regular js/jquery? – aalok89 Jan 15 '18 at 22:06
  • there is no jQuery on NodeJs since there is no HTML DOM to work upon. You should totally replace the $.get(); method with NodeJS's built-in 'http' capability, or maybe use a https://www.npmjs.com/package/request - module. Here's a page about making requests with NodeJs - https://www.twilio.com/blog/2017/08/http-requests-in-node-js.html – Mikser Jan 15 '18 at 22:13
  • You would use Node instead of your MAMP stack. If you are talking about letting the user save a file to their computer, then try looking here https://stackoverflow.com/questions/13405129/javascript-create-and-save-file . If you want to use node for your server, you should go through some basic node tutorials. – skylize Jan 15 '18 at 22:17
  • thanks @Mikser. Guess I had to use ALL nodejs for this. Ok I converted everything (I think) to nodejs and when I run it without the capitalize function, it works great, but I get an error because of the forEach. How would I convert that into proper node? https://codepen.io/aalokt89/pen/ypxJaN (i commented out the capitalize function and labeled it with "THIS DOES NOT WORK") – aalok89 Jan 16 '18 at 01:20

2 Answers2

1

If you are just trying to test out your own data, using consolesave.js for Chrome can save you a lot of time. When I'm initially setting up projects and testing data I've retrieved via ajax and then parsed and re-written, this small script lets you write JSON directly from Chrome (to your downloads folder). I'm not sure where I got this file, but one source is this github repo. https://github.com/bgrins/devtools-snippets/blob/master/snippets/console-save/console-save.js

function capitalize(text) {
    return (!text || !text.length) ?
        text :
        (text[0].toUpperCase() + text.slice(1));
}



(function(console){

    console.save = function(data, filename){
      
        console.log('data is '+data);
        if(!data) {
            console.error('Console.save: No data')
            return;
        }

        if(!filename) filename = 'console'

        if(typeof data === "object"){
            data = JSON.stringify(data, undefined, 4)
        }

        var blob = new Blob([data], {type: 'text/json'}),
            e    = document.createEvent('MouseEvents'),
            a    = document.createElement('a')

        a.download = filename+ '.json'
        a.href = window.URL.createObjectURL(blob)
        a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
        e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
        a.dispatchEvent(e)
    }
})(console)

$.ajax({
 url: 'https://randomuser.me/api/?results=20&nat=us&inc=name,gender,picture&format=pretty',
    type : 'GET',
    dataType:'json',
    success : function(data) {  
        if (!data || !data.results) {
          console.log('no data');
          return
         }
         console.log('got your data')
        //going through 'data' and capitalizing name and gender
        data.results.forEach(function(user) {
            if (user.name) {
                for (var name in user.name) {
                    user.name[name] = capitalize(user.name[name]);
                }
            }
            if (user.gender) {
                user.gender = capitalize(user.gender);
            }
        });

        console.log(data);
        console.save(JSON.stringify(data),'test_data.json');
  }
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Stacey Reiman
  • 666
  • 4
  • 13
0

FINALLY figured it out. After several hours of trial and error, I got it to work! Probably messy and horrible code, but this was a hack project from the get-go anyway. Here's my final code:

// initialize firebase------------------------------------
var firebase = require('firebase');

var config = {
    apiKey: "AIzaSyBjS4dUaqPLhggmdF9hrIwQTH4i4QwjpR4",
    authDomain: "my-user-generator.firebaseapp.com",
    databaseURL: "https://my-user-generator.firebaseio.com",
    projectId: "my-user-generator",
    storageBucket: "my-user-generator.appspot.com",
    messagingSenderId: "317975340395"
  };
var app = firebase.initializeApp(config);
var database = firebase.database();
//-------------------------------------------------------

const got = require('got');
var each  = require('foreach');
var jsonfile = require('jsonfile')

//function to capitalize text
function capitalize(text) {
    return (!text || !text.length) ?
    text :
    (text[0].toUpperCase() + text.slice(1));
}

got('https://randomuser.me/api/?results=20&nat=us&inc=name,gender,picture&format=pretty', {json: true}).then(response => {

        var data = response.body;

        //capitalize names and gender
        each(data.results, function(user) {
            if (user.name) {
                for (var name in user.name) {
                    user.name[name] = capitalize(user.name[name]);
                }
            }
            if (user.gender) {
                user.gender = capitalize(user.gender);
            }
        });

        //create json file
        var file = 'users.json';

        jsonfile.writeFile(file, data, {spaces: 4, EOL: '\r\n'}, function(err) {
            console.error(err)
        });
        console.log(data);

        //write new data to firebase
        database.ref().set(data);

}).catch(error => {
    console.log(error.response.body);
});
aalok89
  • 171
  • 5
  • 14