NODE JS

Node JS guide

Node JS fundamentals

Install NPM packages and NODEMON
1. NPM Init => Npm init
 
2. Install FS => Npm install fs
 
3. Install OS => Npm install os
 
4. Install Lodash => Npm install lodash
 
5. Install Yargs => Npm install yargs
 
6. Start Nodemon=> nodemon app.js
 
7. Stop Nodemon=> ctrl + C
App.js file
const fs = require('fs'); const _ = require('lodash'); const yargs = require('yargs'); const notes = require('./notes.js'); const argv = yargs.argv; var command = argv._[0]; if (command === 'add') { var note = notes.addNote(argv.title, argv.body); if (note) { console.log('Note created'); notes.logNote(note); } else { console.log('Note title taken'); } } else if (command === 'list') { var allNotes = notes.getAll(); console.log(`Printing ${allNotes.length} note(s).`); allNotes.forEach((note) => notes.logNote(note)); } else if (command === 'read') { var note = notes.getNote(argv.title); if (note) { console.log('Note found'); notes.logNote(note); } else { console.log('Note not found'); } } else if (command === 'remove') { var noteRemoved = notes.removeNote(argv.title); var message = noteRemoved ? 'Note was removed' : 'Note not found'; console.log(message); } else { console.log('Command not recognized'); } 
Notes.js
const fs = require('fs'); var fetchNotes = () => { try { var notesString = fs.readFileSync('notes-data.json'); return JSON.parse(notesString); } catch (e) { return []; } }; var saveNotes = (notes) => { fs.writeFileSync('notes-data.json', JSON.stringify(notes)); }; var addNote = (title, body) => { var notes = fetchNotes(); var note = { title, body }; var duplicateNotes = notes.filter((note) => note.title === title); if (duplicateNotes.length === 0) { notes.push(note); saveNotes(notes); return note; } }; var getAll = () => { return fetchNotes(); }; var getNote = (title) => { var notes = fetchNotes(); var filteredNotes = notes.filter((note) => note.title === title); return filteredNotes[0]; }; var removeNote = (title) => { var notes = fetchNotes(); var filteredNotes = notes.filter((note) => note.title !== title); saveNotes(filteredNotes); return notes.length !== filteredNotes.length; }; var logNote = (note) => { console.log('--'); console.log(`Title: ${note.title}`); console.log(`Body: ${note.body}`); }; module.exports = { addNote, getAll, getNote, removeNote, logNote }; 
Notes-data.json
[{"title":"to buy","body":"food"},{"title":"to buy from store","body":"food"},{"title":"things to do","body":"go to post office"}] 
Package.json
{ "name": "notes-node", "version": "1.0.0", "description": "", "main": "app.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "Andrew Mead", "license": "ISC", "dependencies": { "lodash": "^4.13.1", "yargs": "^4.7.1" } } 
Advanced Yargs => App.js
const fs = require('fs'); const _ = require('lodash'); const yargs = require('yargs'); const notes = require('./notes.js'); const titleOptions = { describe: 'Title of note', demand: true, alias: 't' }; const bodyOptions = { describe: 'Body of note', demand: true, alias: 'b' }; const argv = yargs .command('add', 'Add a new note', { title: titleOptions, body: bodyOptions }) .command('list', 'List all notes') .command('read', 'Read a note', { title: titleOptions, }) .command('remove', 'Remove a note', { title: titleOptions }) .help() .argv; var command = argv._[0]; if (command === 'add') { var note = notes.addNote(argv.title, argv.body); if (note) { console.log('Note created'); notes.logNote(note); } else { console.log('Note title taken'); } } else if (command === 'list') { var allNotes = notes.getAll(); console.log(`Printing ${allNotes.length} note(s).`); allNotes.forEach((note) => notes.logNote(note)); } else if (command === 'read') { var note = notes.getNote(argv.title); if (note) { console.log('Note found'); notes.logNote(note); } else { console.log('Note not found'); } } else if (command === 'remove') { var noteRemoved = notes.removeNote(argv.title); var message = noteRemoved ? 'Note was removed' : 'Note not found'; console.log(message); } else { console.log('Command not recognized'); } 

Asynchronous Node JS - weather app

REQUEST & AXIOS Npm packages
1. Install Request => npm install request
 
2. Install Axios => npm install axios
Weather App => App.js
const yargs = require('yargs'); const geocode = require('./geocode/geocode'); const weather = require('./weather/weather'); const argv = yargs .options({ a: { demand: true, alias: 'address', describe: 'Address to fetch weather for', string: true } }) .help() .alias('help', 'h') .argv; geocode.geocodeAddress(argv.address, (errorMessage, results) => { if (errorMessage) { console.log(errorMessage); } else { console.log(results.address); weather.getWeather(results.latitude, results.longitude, (errorMessage, weatherResults) => { if (errorMessage) { console.log(errorMessage); } else { console.log(`It's currently ${weatherResults.temperature}. It feels like ${weatherResults.apparentTemperature}.`); } }); } }); 
Weather App Promise => AppPromise.js
const yargs = require('yargs'); const axios = require('axios'); const argv = yargs .options({ a: { demand: true, alias: 'address', describe: 'Address to fetch weather for', string: true } }) .help() .alias('help', 'h') .argv; var encodedAddress = encodeURIComponent(argv.address); var geocodeUrl = `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}`; axios.get(geocodeUrl).then((response) => { if (response.data.status === 'ZERO_RESULTS') { throw new Error('Unable to find that address.'); } var lat = response.data.results[0].geometry.location.lat; var lng = response.data.results[0].geometry.location.lng; var weatherUrl = `https://api.forecast.io/forecast/4a04d1c42fd9d32c97a2c291a32d5e2d/${lat},${lng}`; console.log(response.data.results[0].formatted_address); return axios.get(weatherUrl); }).then((response) => { var temperature = response.data.currently.temperature; var apparentTemperature = response.data.currently.apparentTemperature; console.log(`It's currently ${temperature}. It feels like ${apparentTemperature}.`); }).catch((e) => {  if (e.code === 'ENOTFOUND') {  console.log('Unable to connect to API servers.'); } else { console.log(e.message); } }); 
Weather App => Geocode.js
const request = require('request'); var geocodeAddress = (address, callback) => { var encodedAddress = encodeURIComponent(address); request({ url: `https://maps.googleapis.com/maps/api/geocode/json?address=${encodedAddress}`, json: true }, (error, response, body) => { if (error) { callback('Unable to connect to Google servers.'); } else if (body.status === 'ZERO_RESULTS') { callback('Unable to find that address.'); } else if (body.status === 'OK') { callback(undefined, { address: body.results[0].formatted_address, latitude: body.results[0].geometry.location.lat, longitude: body.results[0].geometry.location.lng }); } }); }; module.exports.geocodeAddress = geocodeAddress; 
Weather App => Weather.js
const request = require('request'); var getWeather = (lat, lng, callback) => { request({ url: `https://api.forecast.io/forecast/4a04d1c42fd9d32c97a2c291a32d5e2d/${lat},${lng}`, json: true }, (error, response, body) => { if (error) { callback('Unable to connect to Forecast.io server.'); } else if (response.statusCode === 400) { callback('Unable to fetch weather.'); } else if (response.statusCode === 200) { callback(undefined, { temperature: body.currently.temperature, apparentTemperature: body.currently.apparentTemperature }); } }); }; module.exports.getWeather = getWeather;