How to define object in node js - javascript

I am trying to assign a value to an object, but when I try to display it always returns [].
here is a piece of my code
const exspress = require("express");
const aplication = exspress();
//body parser for informaton monggo
const bodyparser = require("body-parser");
//configuration for node aplication
aplication.use(
bodyparser.urlencoded({
extended: false
})
);
const mongose = require("mongoose");
const router = exspress.Router();
const PingModel = mongose.model("Ping");
const ping = require("ping");
var tcpp = require("tcp-ping");
var obj = Array();
var a = 0;
var b = pingtime;
for(a; a<b; a++){
ping.promise.probe(host).then(function(data) {
const storePing = new PingModel();
storePing.hostPing = host;
storePing.hostIp = data.numeric_host;
if (data.alive) {
storePing.hostStatus = "Ok";
} else {
storePing.hostStatus = "Not_ok";
}
if (data.alive) {
storePing.hostLatency = "true";
} else {
storePing.hostLatency = "false";
}
storePing.save();
window.obj = storePing
// return this.obj[a] = storePing;
});
console.log(obj);
}
module.exports = router;
Can you guys tell me how to define an object and fill it with data/value that I use it in separate code/function?

try changing window.obj to obj as your obj is only a variable, it is not on a window object
also, when declaring your object, you have declared it as an Array. If you want an Object, you can use var obj = {};, though are are reassigning it anyway with storePing
also, you would need to move your console.log into the then callback of the promise, since it is async code you have - at the minute, your console.log will fire before the then callback of the promise has executed and thus obj would not yet have the value your are expecting
Something a long the lines of -
const router = exspress.Router();
const PingModel = mongose.model("Ping");
const ping = require("ping");
var tcpp = require("tcp-ping");
var obj = {}; // NOTE, object instead of array, though this gets reassigned anyway, so doesn't really matter
var a = 0;
var b = pingtime;
for(a; a<b; a++){
ping.promise.probe(host).then(function(data) {
const storePing = new PingModel();
storePing.hostPing = host;
storePing.hostIp = data.numeric_host;
if (data.alive) {
storePing.hostStatus = "Ok";
} else {
storePing.hostStatus = "Not_ok";
}
if (data.alive) {
storePing.hostLatency = "true";
} else {
storePing.hostLatency = "false";
}
storePing.save();
obj = storePing // <-- NOTE, no window object
console.log(obj); // <-- NOTE, logging inside the then callback
// return this.obj[a] = storePing;
});
}
module.exports = router;

Related

I have a mapping method that accepts a callback as an argument but I keep getting this error JavaScript

I'm totally confused as to why 'cb' is not a function in my case.
Basically I have a 'Tree' constructor
this.value = value;
this.children = [];
};
Tree.prototype.addChild = function (value){
var newInstance = new Tree(value);
this.children.push(newInstance);
}
Tree.prototype.map = function(cb){
var copyTree = new Tree(this.value); //1
copyTree.value = cb(copyTree.value);
for (var i = 0; i < this.children.length; i++){ // i = 0; 2 i = 0's value is 2
copyTree.addChild(new Tree.prototype.map(cb(this.children[i].value)))
}
return copyTree;
}
and then in the console I've passed in
var root1 = new Tree(1)
var branch1 = root1.addChild(2);
var branch2 = root1.addChild(3);
Now every time I invoke
var newTree = root1.map(function (value) {
return value * 2 })
I keep getting this error.
VM1769 Script snippet %231:13 Uncaught TypeError: cb is not a function
at new Tree.map (VM1769 Script snippet %231:13)
at Tree.map (VM1769 Script snippet %231:19)
at <anonymous>:1:21
I know that my mapping method might not be right but just the fact that 'cb' is not a function confuses me, I'm passing in an anonymous function on the .map call but.. 'cb' is not a function? Why is that?
Inside .map, you have an array of trees to copy inside this.children. Since the array is composed of trees, those trees already have a .map method which you can call to create a copy of that tree. Change
copyTree.addChild(new Tree.prototype.map(cb(this.children[i].value)))
to
copyTree.addChild(this.children[i].map(cb))
function Tree(value) {
this.value = value;
this.children = [];
};
Tree.prototype.addChild = function(value) {
var newInstance = new Tree(value);
this.children.push(newInstance);
}
Tree.prototype.map = function(cb) {
var copyTree = new Tree(this.value);
copyTree.value = cb(copyTree.value);
for (var i = 0; i < this.children.length; i++) {
copyTree.addChild(this.children[i].map(cb))
}
return copyTree;
}
var root1 = new Tree(1)
var branch1 = root1.addChild(2);
var branch2 = root1.addChild(3);
var newTree = root1.map(function(value) {
return value * 2
})
console.log(newTree);
More readably, using modern syntax:
class Tree {
constructor(value) {
this.value = value;
this.children = [];
}
addChild(value) {
const newInstance = new Tree(value);
this.children.push(newInstance);
}
map(cb) {
const copyTree = new Tree(this.value);
copyTree.value = cb(copyTree.value);
for (const child of this.children) {
copyTree.addChild(child.map(cb))
}
return copyTree;
}
}
const root1 = new Tree(1)
const branch1 = root1.addChild(2);
const branch2 = root1.addChild(3);
const newTree = root1.map(value => value * 2);
console.log(newTree);

Parse Cloud Code Promises in a for loop

As the title states, I'm having trouble with Promises in Parse.
I'm struggling to firstly understand exactly how Promises themselves work, especially in Parse.
I have been stuck on this for about three weeks and the closest I've come to a solution is having an empty array returned.
What I'm trying to do is scrape a site and then create objects from the table (this is working)
Where there trouble comes in, is I am then running a for loop on the results and querying each Dam name to get the resulting objectid from the database.
Here is my code:
var c = new Crawler({
maxConnections: 10,
// This will be called for each crawled page
callback: function(err, res, done) {
if (err) {
console.log(err);
} else {
var $ = res.$;
// $ is Cheerio by default
//a lean implementation of core jQuery designed specifically for the server
console.log($("title").text());
}
done();
}
});
The Function which Creates objects from the Dom and adds them to an array:
function getDamObjects(Dom) {
var dom = Dom;
var LevelObjects = [];
for (i = 1; i < dom.length - 1; i++) {
var TableRow = dom.eq(i);
var NameString = TableRow.children().eq(0).text();
var RiverString = TableRow.children().eq(1).text();
var FSCString = TableRow.children().eq(4).text();
var ThisWeekString = TableRow.children().eq(5).text();
var LastWeekString = TableRow.children().eq(6).text();
var LastYearString = TableRow.children().eq(7).text();
NameString = NameString.replace('#', '');
NameString = NameString.replace('$', '');
NameString = NameString.replace('&', '');
NameString = NameString.replace('#', '');
ThisWeekString = ThisWeekString.replace('#', '');
ThisWeekString = ThisWeekString.replace('$', '');
ThisWeekString = ThisWeekString.replace('&', '');
ThisWeekString = ThisWeekString.replace('#', '');
LastWeekString = LastWeekString.replace('#', '');
LastWeekString = LastWeekString.replace('$', '');
LastWeekString = LastWeekString.replace('&', '');
LastWeekString = LastWeekString.replace('#', '');
LastYearString = LastYearString.replace('#', '');
LastYearString = LastYearString.replace('$', '');
LastYearString = LastYearString.replace('&', '');
LastYearString = LastYearString.replace('#', '');
var level = {};
/*
getDamObject(NameString).then(function(DamObject){
let DamID = DamObject.id;
*/
level['Dam'] = NameString; //DamID;
level['ThisWeek'] = ThisWeekString;
level['LastWeek'] = LastWeekString;
level['LastYear'] = LastYearString;
LevelObjects.push(level);
};
return LevelObjects;
};
The Get Dam Object Code:
function getDamObject(Dam) {
var promise = new Parse.Promise();
var query = new Parse.Query("DayZeroDams");
query.equalTo("Name", Dam);
query.first().then(function(DamObject) {
promise.resolve(DamObject);
}, function(error) {
promise.reject(error);
});
return promise;
}
The Cloud Code Called:
Parse.Cloud.define('jsdom', function(request, response) {
c.queue([{
uri: 'xxxxxx',
// The global callback won't be called
callback: function(err, res, done) {
if (err) {
response.error(err);
} else {
var $ = res.$;
var ResultsArray = [];
var dom = res.$('#mainContent_tw').children('tr');
return Parse.Promise.as().then(function() {
var promise = Parse.Promise.as();
var LevelObjects = getDamObjects(dom);
_.each(LevelObjects, function(DamLevel) {
promise = promise.then(function() {
var Name = DamLevel["Dam"];
var query = new Parse.Query("DayZeroDams");
query.equalTo("Name", Name);
return query.first().then(function(result) {
let damID = result.id;
ResultsArray.push(damID);
return Parse.Promise.as();
}, function(error) {
response.error(error);
});
});
});
return promise;
}).then(function() {
response.success(ResultsArray);
}, function(error) {
response.error(error);
});
//response.success(LevelObjects);
}
done();
}
}]);
});
Please take note that I am fairly novice when it comes to Javascript, I have only recently started learning it in order to work with my server code.
Convert getDamObjects into an async function and then await the result of each row, pushing it to the array:
function replaceSymbols(input) {
return input.replace(/[#\$&#]/g, '');
}
async function getDamObjects(Dom) {
const dom = Dom;
const levelObjects = [];
for (let i = 1; i < dom.length - 1; i++) {
const children = dom.eq(i).children();
const NameString = replaceSymbols(children.eq(0).text());
const RiverString = children.eq(1).text();
const FSCString = children.eq(4).text();
const ThisWeek = replaceSymbols(children.eq(5).text());
const LastWeek = replaceSymbols(children.eq(6).text());
const LastYear = replaceSymbols(children.eq(7).text());
const Dam = await getDamObject(NameString);
levelObjects.push({
Dam,
ThisWeek,
LastWeek,
LastYear,
});
}
return levelObjects;
}
Remember that now that getDamObjects is an async function, it will return a Promise that resolves to the array once iterations are complete. Consume it using await getDamObjects in another async function (or use .then)

Use the value of a variable in another file

Currently I am using protractor and using page object, so there is a file that I get the value of an element in a variable, but I need to call this value in another file.
vehiclePage.js
/*jshint esversion: 6 */
var basePage = require('./basePage.js');
var homePage = require('./homePage.js');
var VehiclePage = function() {
this.storeVehicleData = function() {
this.pessengersRuntValue = element(by.id('preview_ocupantes_runt')).getText();
};
};
VehiclePage.prototype = basePage; // extend basePage...
module.exports = new VehiclePage();
Now I need to use the value of the above variables in another file
checkoutPage.js
/*jshint esversion: 6 */
var basePage = require('./basePage.js');
var homePage = require('./homePage.js');
var CheckoutPage = function() {
this.getRuntValue = element(by.css('.mb10'));
this.compareValues = function() {
expect(this.getRuntValue.getText()).toContain(this.pessengersRuntValue);
};
};
CheckoutPage.prototype = basePage; // extend basePage...
module.exports = new CheckoutPage();
How can I make it work?
If you are following Page Object Design Pattern, I would say that the test should not be on the page object. I will write something like this.
VehiclePage.js
var VehiclePage = function(){
// if this is a browser testing something like this
browser.get('/vehicle');
};
VehiclePage.prototype = Object.create({}, {
runt: {
get: function(){
return element(by.id('preview_ocupantes_runt'));
}
}
});
module.export = VehiclePage;
CheckOutPage.js
var CheckOutPage = function(){
// if this is a browser testing something like this
browser.get('/checkout');
};
CheckOutPage.prototype = Object.create({}, {
runt: {
get: function(){
return element(by.css('.mb10'));
}
}
});
module.export = CheckOutPage;
TheTest.js
var VehiclePage = require('VehiclePage');
var CheckOutPage = require('CheckOutPage');
describe('testing something', () => {
var vehicle = new VehiclePage();
var checkout = new CheckOutPage();
it('should contain', () => {
expect(checkout.runt.getText()).toContains(vehicle.runt.getText());
});
});
One way to do this would be to pass a state object to both pages.
var VehiclePage = require('./vehiclePage.js');
var CheckoutPage = require('./checkoutPage.js');
class StateStorage {
constructor(){
this.savedVariable = null;
}
}
var state = new StateStorage();
var vehiclePage = new VehiclePage(state);
var checkoutPage = new CheckoutPage(state);
Then you can manipulate and access the state from both new pages.

Node / statSync issues

I'm trying to log an array of numerically named sub-directories in "e:\subdirectory\" by using fs.statSync but I keep getting the error "module.exports" is not a function; to my understanding, this is exactly how I'm supposed to export the data
I'm using the synchronous version because I want the array to finish populating before it's exported.
this is for a "proof of concept", I plan on serving an html doc and pushing this array to an input field
here is the code...
checke.js
var fs = require('fs');
function checkE() {
for (var i = 1, accts = [], path = "e:\\subdirectory\\"; i <10000; i++ ) {
var target = fs.statSynch(path + i.toString())
if (target.isDirectory()) { accts.push(i) }
}
}
module.exports(checkE)
init.js
var checke = require('./checke.js')
console.log(checke)
You need to assign something to module.exports not call it like a function. module.exports is an object
checke.js
var fs = require('fs');
module.exports = {
checkE: function checkE() {
var accts = [];
var path = 'e:\\subdirectory\\';
for (var i = 1; i <10000; i++ ) {
var target = fs.statSync(path + i.toString())
if (target.isDirectory())
accts.push(i);
}
return accts;
}
}
init.js
var checke = require('./checke.js');
checke.checkE();

Javascript: Calling private in a outside javascript file with JSON data

I am trying to call the method getTitulo, getDuracion and getLink inside the cancion.js file but when i call the function it returns the following error: "listaCanciones_Lcl[i].getTitulo is not a function". I have searched in different websites but i didnt got lucky with finding an answer. Hopefully someone here can give me some help, i will gladly appreciate it!
//Logic.js file
var listaCanciones = [],
ejecuTitulo = '',
ejecuDuracion = '',
ejecuLink = '';
var btnGenerarLista = document.getElementById("addList").addEventListener("click", agregarCanc);
var btnAgregarLista = document.getElementById("gnrList").addEventListener("click", llenarTabla);
function agregarCanc (){
var nameSong = document.querySelector('#nameSong').value;
var duraSong = document.querySelector('#duraSong').value;
var linkSong = document.querySelector('#linkSong').value;
var objCancion = new Cancion(nameSong, duraSong, linkSong);
listaCanciones.push(objCancion);
var listaCancionesJson = JSON.stringify(listaCanciones);
localStorage.setItem('json_canciones', listaCancionesJson);
}
function llenarTabla (titulo){
var celdaTitulo = document.querySelector('#tituloList'),
celdaDuracion = document.querySelector('#duracionList'),
celdaLink = document.querySelector('#linkList'),
listaCanciones_Lcl = JSON.parse(localStorage.getItem('json_canciones'));
for(var i=0; i<listaCanciones_Lcl.length;i++){
// Acceder a lista canciones
I am getting an error in this line, where is says "getTitulo" is not a function but i dont really know why?
var nodoTextoTitulo = document.createTextNode(listaCanciones_Lcl[i].getTitulo()),
nodoTextoDuracion = document.createTextNode(listaCanciones_Lcl[i].getDuracion()),
nodoTextoLink = document.createTextNode(listaCanciones_Lcl[i].getLink());
// Create td
var elementoTdTitulo = document.createElement('td'),
elementoTdDuracion = document.createElement('td'),
elementoTdLink = document.createElement('td');
// Celda Id Append Child
elementoTdTitulo.appendChild(nodoTextoTitulo);
elementoTdDuracion.appendChild(nodoTextoDuracion);
elementoTdLink.appendChild(nodoTextoLink);
// Fila Append Child
celdaTitulo.appendChild(elementoTdTitulo);
celdaDuracion.appendChild(elementoTdDuracion);
celdaLink.appendChild(elementoTdLink);
}
}
//Cancion.js File
var Cancion = function(pTitulo, pDuracion, pLink){
var id = 0;
var titulo = pTitulo;
var duracion = pDuracion;
var link = pLink;
this.getId = function (){
return id;
};
this.setTitulo = function (pTitulo){
titulo = pTitulo;
};
this.getTitulo = function(){
return titulo;
};
this.setDuracion = function(pDuracion){
duracion = pDuracion;
};
this.getDuracion = function(){
return duracion;
};
this.setLink = function (pLink){
link = pLink;
};
this.getLink = function(){
return link;
};
};
First, make sure you are loading the Cancion.js file before the others in your HTML. Your problem is that when you parse the JSON back out of local storage, Cancion is not a known object, so getTitulo is undefined. You'll have to do listaCanciones_Lcl[i].titulo; instead.
And another change you'll need is to loosen the scope of your variables. The reason you need this.x = pX is because before JSON.stringify(new Cancion(1, 2, 3)) just returned "{}". With this code it returns "{"id":0,"titulo":1,"duracion":2,"link":3}", which I think is what you were after.
function Cancion(pTitulo, pDuracion, pLink){
this.id = 0;
this.titulo = pTitulo;
this.duracion = pDuracion;
this.link = pLink;
this.getId = function (){
return this.id;
};
this.setTitulo = function (pTitulo){
this.titulo = pTitulo;
};
this.getTitulo = function(){
return this.titulo;
};
this.setDuracion = function(pDuracion){
this.duracion = pDuracion;
};
this.getDuracion = function(){
return this.duracion;
};
this.setLink = function (pLink){
this.link = pLink;
};
this.getLink = function(){
return this.link;
};
};
var objWithFunction = {
name: 'Object with Function',
getName: function() { return this.name }
};
undefined
objWithFunction.getName() // --> "Object with Function"
var string = JSON.stringify(objWithFunction)
string // -=> "{"name":"Object with Function"}"
JSON is for data only..
Better you create a model, and fill it with data.. but this model has to exist in your application.. or you load the model parallel to your data..
function SomeThing() {};
SomeThing.prototype.getName = function() { return this.name };
var Thing1 = new SomeThing(JSON.parse("{name:'ThingOne'}"));
Thing1.getName(); // ThingOne

Categories