Node.js – Functions



Node.js – Functions

0 0


NodeJS-Introduction-Part-II

Node.js introduction to functions

On Github SUNY-Albany-CCI-LearningEncounters / NodeJS-Introduction-Part-II

Node.js

Functions

Created by Luis Ibanez

Node.js Functions by Luis Ibanez is licensed under a Creative Commons by Attribution 4.0 License Apache 2.0 License

Javascript

Server-Side

Node.js

Functions

Let's write

our first

Function

Launch Vim from the command line prompt

to create a new file

vim helloworld.js

Type in the file the following

var sayhello = function() {
  console.log("Hello World");
}

sayhello();

Save the file and quit the editor

Run the code with nodejs

nodejs helloworld.js

You should see

"Hello World"

Let's write

our second

Function

Launch Vim from the command line prompt

to create a new file

vim visitcountries.js

Type in the file the following

var visitcountries = function() {
  var world = {};
  world.asia = {};
  world.africa = {};
  world.america = {};
  world.asia.japan = {};
  world.asia.japan.tokyo = {};
  world.asia.japan.kyoto = {};

  console.log("Visited %j",world);
}

visitcountries();

Run the code with nodejs

nodejs visitcountries.js

You should see

Visited {"asia":{"japan":{"tokyo":{},"kyoto":{}}},"africa":{},"america":{}}

Let's improve

the formatting

Edit the file

vim visitcountries.js

Replace the line:

console.log("Visited %j",world);

With the line:

console.log( JSON.stringify(world,null,2) );

Run the code again

nodejs visitcountries.js

Let's get data

from the Web

Create a new file

vim weatherdata.js

Type in the file the following

var http = require('http');

var options = {
  host: 'api.openweathermap.org',
  path: '/data/2.5/weather?q=Albany,US'
};

callback = function(response) {

  response.on('data', function (inputdata) {
    var jsonstr = JSON.parse(inputdata);
    console.log(JSON.stringify(jsonstr,null,2));
  });

}

http.request(options, callback).end();

Save the file

and quit the editor

Run the new code

nodejs weatherdata.js

Analyze

the output

Let's get data

for any city

Edit the file

vim weatherdata.js

Edit the first lines to become:

var http = require('http');

var city    = process.argv[2];
var country = process.argv[3];

var options = {
  host: 'api.openweathermap.org',
  path: '/data/2.5/weather?q=' + city + ',' + country
};

Run the code again

but this time add the arguments

nodejs weatherdata.js Albany US

Let's get

more data!

Find out

the weather

from three cities

Breath!

Smile!