please explain for me how this line work
app.get("/speak/:animal", function(req, res) {
var sounds = {
pig: "OINK",
cow: "MOO",
dog: "WOOF WOOF",
cat: "I hate humans",
goldfish: "..."
};
var animal = req.params.animal.toLowerCase();
var sound = sounds[animal];
res.send("The " + animal + " says '" + sound + "'");
});
and this line too please
app.get("/repeat/:message/:times", function(req, res) {
var message = req.params.message;
var times = Number(req.params.times);
var result = "";
for(var i = 0; i < times; i++) {
result += message + " ";
}
res.send(result);
});
The first one:
// Listens to all the get requests on the url path /speak/anything
// :animal is a placeholder, anything you pass in the url will be be available in the url param animal.
app.get("/speak/:animal", function(req, res){
// JSON object with a key value pair.
var sounds = {
pig: "OINK",
cow: "MOO",
dog: "WOOF WOOF",
cat: "I hate humans",
goldfish: "..."
};
// Converts the request parameter 'anything' in the url to a lower case string.
var animal = req.params.animal.toLowerCase();
// Tries to find the sound in the sounds object since 'anything' is no key it wont find a suitable value for the sound.
var sound = sounds[animal];
// Responds to the request with the resolved sound.
res.send("The " + animal + " says '" + sound + "'");
The second one
// Let us consider that the request /repeat/received/10
app.get("/repeat/:message/:times", function(req, res){
// the /received in the url will be available to access under the req.param.messages
var message = req.params.message;
// message = received
// Converting the times string 10 passed in the url to a number
var times = Number(req.params.times);
var result = "";
// loop will run from 0 to 9 and keep appending to the string result
for(var i = 0; i < times; i++){
result += message + " ";
}
// At the end of the for loop
// result will contain = 'received received received' 7 more time ...
// will send the response to the request.
res.send(result);
});
Related
I am trying to have a node js script write some coordinates to a csv file for use in a Newman CLI script. I have the following:
const axios = require('axios');
var move_decimal = require('move-decimal-point');
var sLat = 45.029830;
var sLon = -93.400891;
var eLat = 45.069523;
var eLon = -94.286001;
var arrLatLon = []
axios.get('http://router.project-osrm.org/route/v1/driving/' + sLon + ',' + sLat + ';' + eLon + ',' + eLat + '?steps=true')
.then(function (response) {
for (let i = 0; i < response.data.routes[0].legs.length; i++) {
//console.log(response.data)
for (let ii = 0; ii < response.data.routes[0].legs[i].steps.length; ii++) {
//console.log('leg ' + i + " - step " + ii + ": " + response.data.routes[0].legs[i].steps[ii].maneuver.location[1] + "," + response.data.routes[0].legs[i].steps[ii].maneuver.location[0]);
// Declaring Latitude as 'n' & Longitude as 'nn' for decimal calculations
var n = response.data.routes[0].legs[i].steps[ii].maneuver.location[1]
var nn = response.data.routes[0].legs[i].steps[ii].maneuver.location[0]
// Latitude calculatiuons to make 'lat' values API friendly
var y = move_decimal(n, 6)
var p = Math.trunc(y);
// Longitude calculations to make 'lon' values API friendly
var yy = move_decimal(nn, 6)
var pp = Math.trunc(yy);
arrLatLon.push(p + "," + pp);
}
console.log(arrLatLon)
}
})
I have been looking through and trying numerous different tutorials/code snippets regarding writing the array elements from arrLatLon to an output file on my local machine, but none have been successful. The current code outputs the lat,lon correctly, console.log(arrLatLon) outputs:
[ '45029830,-93400894',
'44982812,-93400740',
'44977444,-93400530',
'44973116,-93410884',
'44971101,-93450400',
'45035514,-93766885',
'45035610,-93766886',
'45081631,-94286752',
'45070849,-94282026' ]
any help would be greatly appreciated. Thanks.
With nodejs you can easily write files using the fs module
const fs = require('fs');
fs.writeFile("/tmp/test", "Hey there!", function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
in your case you can simply do something like
const fs = require('fs');
// I'm converting your array in a string on which every value is
// separated by a new line character
const output = arrLatLon.join("\n");
// write the output at /tmp/test
fs.writeFile("/tmp/test", output, function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
Let me forward you to this question for more information Writing files in Node.js
I'm very new to this, and I was hoping to get some clarity in this:
Whenever I run this code (PS: boardGames, is an array in a separate doc) It seems to work, but the first answer is always "undefined". Why is that? and how can I fix it?
Thanks!
var message;
var games;
var search;
var i;
function print(message) {
var outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
function gamestoPlay( games ) {
var topGames = '<h3> Game: ' + boardGames[i].name +'</h3>';
topGames += '<p> Minimum Players: ' + boardGames[i].idealMinPlayers + '</p>';
topGames += '<p> Maximum Players: ' + boardGames[i].idealMaxPlayers + '</p>';
return topGames
}
search = parseInt(prompt('How many people are coming?'));
for (i = 0; i < boardGames.length; i += 1) {
games = i;
if ( search >= boardGames[i].idealMinPlayers && search <= boardGames[i].idealMaxPlayers) {
message += gamestoPlay();
print(message);
}
}
Because you didn't initialize message.
When you do
message += gamesToPlay();
it first has to convert message to a string so it can concatenate to it. Since you didn't initialize message, its value is undefined, and when this is converted to a string it becomes "undefined", and then the result of gamesToPlay() is concatenated to that.
Change the initialization to:
var message = "";
I am very new to redis & node and at the moment I am trying to loop through some test hash keys that i have created and print out to screen the results. Here is the result I expect to see:
{ "aaData": [['Tim Osbourne'],['Joe Bloggs'],['John Doe'],['Perry Coke'],['Will Holmes'],['Steven Smith']}
but instead I get this result:
{ "aaData": [[],[],[],[],[],[],]}'Tim Osbourne','Joe Bloggs','John Doe','Perry Coke','Will Holmes','Steven Smith',
Here is my code:
app = require('../app');
var redis = require("redis"),
client = redis.createClient();
routes = require('./');
var key_types = '';
client.keys("*", function (err, all_keys) {
key_types += '{ "aaData": [';
all_keys.forEach(function (key, pos) { // use second arg of forEach to get pos
key_types += "[";
client.hmget([key, 'Owner of space'], function(err, field_val){
key_types = key_types + "'" + field_val + "',";
});
key_types += "],";
});
key_types += "]}";
});
app.get('/table_data', function(req, res){
res.render('table_data', { keys: key_types});
});
You should not do a keys *
It does not work because hmget is asynchronous, you should use the async module (async.map) for that.
What is the goal of [key, 'Owner of space'] since 'Owner of space' will always yield the same result?
I am trying to build a array in my socket io server and sending it to the client.
var roomList = io.sockets.manager.rooms;
// new Array to save the clients per room
var clientsPerRoom = new Array();
//for (var i = 0; i < roomList.length; i++) {
for (var room in roomList) {
room = room.replace("/", "");
// get the clients per room
var clients = io.sockets.clients(room).length;
// saving it in the array at the name of the room
clientsPerRoom[room] = clients;
}
// transmit it to the client
io.sockets.emit('roomList', roomList, clientsPerRoom);
On the client side
var clients = 1;
for (room in roomList) {
if (room.length > 0) {
room = room.replace("/", "");
clients = clientsPerRoom[room];
console.log("ROOM: '" + room + "' has '" + clients + "' CLIENTS");
}
}
At the client, "clientsPerRoom" is "[]" (empty?), and so "clients" is "undeined".
What am I doing wrong?
At the console log from the server are the values 1 if a user is connectet. If more users are online then its still 1 but at least it should send this value to the client.
Thanks
Finaly I solved it:
var clients = io.sockets.clients(room).length;
// has to look like this:
//clientsPerRoom = {"test" : 3, "xyz" : 4};
clientString = '"' + room + '" : "' + clients + '",' + clientString;
console.log("clientsPerRoom[" + room + "] : " + clientsPerRoom[room]);
console.log("__END OF LOOP__");
}
}
//cut the "," et the end of the string (else: ERROR!)
clientString = clientString.substr(0, clientString.length-1);
// parse it with JSON to pretend beeing a object
clientsPerRoom = JSON.parse('{' + clientString + '}');
// now send it to the client
io.sockets.emit('roomList', roomList, clientsPerRoom, totalClients);
Now another problem is, that
var clients = io.sockets.clients(room).length;
is always 1...
Even solved yet.
Problem was: io.sockets.clients(room) only counts users who accepted webcam access, otherwise the are not "really" in the room yet.
Greetings
I have spent a whole day on this, googling and searching for answers but still could not figure out.
My code is a bit long and it works well in Firefox but gets "Uncaught SyntaxError: Unexpected token u " from Chrome.
Can anyone points me out where I am wrong? Thanks in advance!
// when the page loads, list all the current contacts
$(document).ready(function(){
// check if localStorage database exists
if(!localStorage.getItem("customerDatabase")){
// define a JSON object to hold all current address
var contacts = {
"users":[
{
"id":"1",
"name":"dennis",
"email":"dennisboys#gmail.com"
},
{
"id":"2",
"name":"zoe",
"email":"zoeisfemale#gmail.com"
}
]
} // end of contacts JSON object
// stringify the object
var stringObject = JSON.stringify(contacts);
// store it into localStorage database
var storedDatabase = localStorage.setItem("customerDatabase", stringObject);
} else {
// list all customers upon page loads
listJSONCustomers();
}
// list all current contacts from JSON object in localStorage
function listJSONCustomers(){
var displayHTML = "";
var i;
// get the data from localStorage
var storedDatabase = localStorage.getItem("customerDatabase");
// parse the data from string to JSON object
var parseObject = JSON.parse(storedDatabase);
// access the users key of the JSON object
var userObject = parseObject.users;
// get the length of the object (how many customers the database has)
var contactsLength = userObject.length;
for(i=0; i<contactsLength; i++){
var trElement = '<tr id="address' + (i+1) + '">';
var tdId = '<td id="id' + (i+1) + '">' + userObject[i].id + '</td>';
var tdName = '<td id="name' + (i+1) + '">' + userObject[i].name + '</td>';
var tdEmail = '<td id="email' + (i+1) + '">' + userObject[i].email + '</td>';
var tdButton = '<td id="button"><button id="editButton' + userObject[i].id + '">Edit</button> | <button id="deleteButton' + userObject[i].id + '">Delete</button></td>';
displayHTML += trElement + tdId + tdName + tdEmail + tdButton + '</tr>';
}
$('#address_list').html(displayHTML);
}
// add customer to database
$('#saveCustomer').click(function(){
if( $('#customerName').val() !== "" && $('#customerEmail').val() !== "" ){
var customerName = $('#customerName').val();
var customerEmail = $('#customerEmail').val();
// get the data from localStorage
var storedDatabase = localStorage.getItem("customerDatabase");
// parse the data from string to JSON object
var parseObject = JSON.parse(storedDatabase);
// access the users key of the JSON object
var userObject = parseObject.users;
// get the new entry
var newCustomerObject = {
"id": userObject.length + 1,
"name": customerName,
"email": customerEmail
};
// push the new entry into the object
userObject.push(newCustomerObject);
// convert the object into string for localStorage
var stringObject = JSON.stringify(parseObject);
// store the JSON object into localStorage
var storedDatabase = localStorage.setItem("customerDatabase", stringObject);
// list all customes again every time a database receives a new entry
listJSONCustomers();
} else {
alert("Please enter customer's name and email.");
}
}); // end of $('#saveCustomer').click();
});
At some point, something you did corrupted the value of your LocalStorage for that key. LocalStorage can only store strings, so if you pass anything else to it, it will convert it to a string. Since your value is 'undefined', that means that at some point, you probably did something like this on accident:
var value;
localStorage.setItem('key', value);
In this case, value is undefined, which is not a string. When this gets saved, it will be converted however. Unfortunately, "undefined" is not valid JSON. That means that when it tries to parse, it will throw an exception.
To fix your issue, you should clear the bad value out with removeItem.
localStorage.removeItem("customerDatabase");