NodeJS inherits - node.js

I've created some scripts and instantiated them on my main script
var eagle1 =new Fleet.F15c(456);
var eagle2 = new Fleet.F15c(123);
var falcon1 = new Fleet.F16(111);
var guardian1 = new Fleet.F14(789);
and have some functions
And now I wanna create a wing - so when the wing is ordered to do something, all the planes assigned to that wing will execute.
I created a 'wing command' script that should have 2 functions that will be called from the main script:
AssignCommand (orderName, planefunction) ->logs the plane function listener to the event emitter of that wing
ExecuteCommand (orderName) -> emits orderName
var EventEmitter = require('events');
var util = require('util');
util.inherits(WingCommand,EventEmitter);
module.exports = WingCommand;
function WingCommand(){
}
But when I created the 1st func
WingCommand.prototype.AssignCommand = function (CommandName , PlaneFunc(data=null)){
this.on(CommandName,PlaneFunc(data));
}
I did not manage figure out the unexpected token on this line
WingCommand.prototype.AssignCommand = function (CommandName , PlaneFunc(data=null)){
I tried some tutorials but did not find a solution
will appreciate your help

Related

How node-modules are implemented in node.js , how function implemention and creating instance are same in socket.io

const io = require('socket.io')();
// or
const Server = require('socket.io');
const io = new Server();
I am confused with following syntax
1) what is socket.io (is it a class or interface i checked the documention in node.js it showed be interface )
2)If it is interface i think we have to use class for using it (i didn't see any documentation to implement interface in javascript )
3) for understanding i tried the following (created 2 files)
example.js
module.exports = function () {
console.log("welcome to javascript");
}
use.js
let imp = require('./example')()
From following Link i have learned about require [https://nodejs.org/en/knowledge/getting-started/what-is-require/][1]
Now i am confused how socket is implemented and how the following 2 syntax's are equal
If socket is a function we can call by
const io = require('socket.io')();
If it is a class we generally do the following (create a instance and use it )
const Server = require('socket.io');
const io = new Server();
But in the documention they said both the syntax are equal how ?
One is for excuting the module.exports and one is used for instancing a class how both are equal
When you do this:
let x = require('someModule');
The value of x is whatever the module sets the module.exports value to in the module. It can literally be anything. It's entirely up to the module what they assign to that. It is often an object (with properties), but it can also be a function and sometimes it's even a function with properties.
To see what socket.io assigns to module.exports, we can go right to the source where we see:
module.exports = Server;
So, then we go look at what is Server and find this:
function Server(srv, opts){
if (!(this instanceof Server)) return new Server(srv, opts);
if ('object' == typeof srv && srv instanceof Object && !srv.listen) {
opts = srv;
srv = null;
}
opts = opts || {};
this.nsps = {};
this.parentNsps = new Map();
this.path(opts.path || '/socket.io');
this.serveClient(false !== opts.serveClient);
this.parser = opts.parser || parser;
this.encoder = new this.parser.Encoder();
this.adapter(opts.adapter || Adapter);
this.origins(opts.origins || '*:*');
this.sockets = this.of('/');
if (srv) this.attach(srv, opts);
}
From that, we can see that it is a constructor function that can be called as either:
const x = new Server(...);
or as:
const x = Server(...);
So, the answer is as follows:
require('socket.io') gives you a constructor function.
That constructor function can be caller either with new or just as a regular function and it adapts to return the same thing, a new server object.
So, when you do this:
const server = require('socket.io')();
it first gets the exported constructor function and then calls it and assigns the newly created object to the server variable.
1) what is socket.io (is it a class or interface i checked the documentation in node.js it should be interface )
socket.io on the server exports a constructor function for creating a server object. It can be called either as a regular function or with new.
2)If it is interface i think we have to use class for using it (i didn't see any documentation to implement interface in javascript )
It's a function. Javascript doesn't have a specific type called an interface. The socket.io code defines a constructor the older fashioned way (before the class keyword existed) though the outcome is largely the same. It defines a constructor function that, when called will create an object of the desired type.
3) Now i am confused how socket is implemented and how the following 2 syntax's are equal
In Javascript, these two different pieces of code create the same server object:
const io = require('socket.io');
const server = io();
and
const server = require('socket.io')();
The second is just a shortcut that doesn't assign the intermediate result from require('socket.io') to a variable, but rather just calls it directly. It will work like this only when the first function call returns a function. So, the first syntax gets a function, assigns it to the io variable and then calls it. The second syntax gets the function and immediately calls it without assigning it to a variable. In both cases the result of getting the function and calling it ends up in the server variable.

Get new object from another class nodejs

Ok so I have a class that contains
Object JS
var GameServer = require("./GameServer");
var gameServer = new GameServer();
GameServer() contains
GameServer JS
function GameServer() {
// Startup
this.run = true;
this.lastNodeId = 1;
this.lastPlayerId = 1;
this.clients = [];
this.largestClient; // Required for spectators
this.nodes = [];
this.nodesVirus = []; // Virus nodes
this.nodesEjected = []; // Ejected mass nodes
this.nodesPlayer = []; // Nodes controlled by players
}
Now, what im trying to acheive is getting gameServer from ObjectClass
In my class i've tried
new JS
var ObjectClass = require("./ObjectClass");
var gameServer = ObjectClass.gameServer;
But from this way, I won't be able to grab the class GameServer() properties. I'm new to node and im sorry I have to ask this question. I'm currently stuck right now
When I try to grab clients from GameServer
var ObjectClass = require("./ObjectClass");
var gameServer = ObjectClass.gameServer;
gameServer.clients.length;
I get error, clients is undefined. Any way around this?.
I cannot modify GameServer nor Object js.. Basicly im making a script attacthed to a script for extra functionalities.
You are missing the exports of your files so when doing require(file) you're getting and empty object {}..
For gameServer you should be doing something like:
'use strict';
function GameServer() {
// Startup
this.run = true;
this.lastNodeId = 1;
this.lastPlayerId = 1;
this.clients = [];
this.largestClient; // Required for spectators
this.nodes = [];
this.nodesVirus = []; // Virus nodes
this.nodesEjected = []; // Ejected mass nodes
this.nodesPlayer = []; // Nodes controlled by players
}
module.exports = exports = GameServer;
ObjectClass
'use strict';
var GameServer = require("./GameServer");
var gameServer = new GameServer();
exports.gameServer = gameServer;
You need to understand that require cache the value returned by the file, so you would be using a singleton of gameServer.

Access variable in main node file from an imported file

//in app.js
var x = require("x.js");
var instanceX = new x();
require("./Weather")();
//in Weather.js
instanceX.getName();
In this case instanceX wouldn't exist when referenced from Weather.js. How do I make instanceX accessible in Weather.js?
There are a number of different ways to approach this in module design. One simple way is to just pass the variable to the weather.js constructor:
//in app.js
var x = require("x.js");
var instanceX = new x();
require("./Weather")(instanceX);
//in Weather.js
var instanceX;
module.exports = function(ix) {
instanceX = ix;
}
// then elsewhere in the module
instanceX.getName();
I refer to this as the "push" model because you're pushing things to the module that you want to share with it.

Using a helper class easily in expressjs

I'm using a pretty barebones expressjs app and want to add a library/helper to store some useful code. Ideally, I'd like it to work as a module. However, I'm unable to get it to work. Here's what I've got:
// helpers/newlib.js
var NewLib = function() {
function testing() {
console.log("test");
}
};
exports.NewLib = NewLib;
.
// controllers/control.js
var newlib = require('../helpers/newlib').NewLib;
var helper = new NewLib();
helper.testing();
.
The error I get is ReferenceError: NewLib is not defined. I followed the design pattern (of how exports works) based on another simple module I downloaded.
What am I doing wrong?
There are two problems with your code.
First, you are assigning the NewLib function from helpers/newlib.js to newlib var, so you should use new newlib() not new NewLib():
// controllers/control.js
var newlib = require('../helpers/newlib').NewLib;
var helper = new newlib(); // <--- newlib, not NewLib
helper.testing();
Or you can rename your variable to NewLib:
// controllers/control.js
var NewLib = require('../helpers/newlib').NewLib;
var helper = new NewLib(); // <--- now it works
helper.testing();
Second, the testing function is not accessible outside the constructor scope. You can make it accessible by assigning it to this.testing for instance:
// helpers/newlib.js
var NewLib = function() {
this.testing = function testing() {
console.log("test");
}
};

Unexpected value for 'this' in express.js instantiated controllers

'this' does not appear to refer to the instantiated budget controller object. Instead it seems to refer to the global object. Does anyone know why this is?
I've defined a budget model. Injected into the controller and I'm attempting to simply generate a random 6 char string when I hit /budgets in my app. Instead this.DEFAULT_SLUG_LENGTH is undefined and I can't figure out why.
This is a dumbed down test case illustrating the issue with 'this'. I have a similar problem when referencing the injected this.budget within another function to query the db based on the slug value.
//models/budget.js
var Schema = require('jugglingdb').Schema;
var schema = new Schema('postgres',{url:process.env.DATABASE_URL});
var Budget = schema.define('budgets',{
total: Number,
slug: String
});
module.exports = Budget;
====================
//controllers/budget.js
function BudgetController (budget) {
this.budget = budget;
};
BudgetController.prototype.DEFAULT_SLUG_LENGTH = 6;
BudgetController.prototype.generateSlug = function (req,res) {
var slug = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < this.DEFAULT_SLUG_LENGTH; i++) {
slug += possible.charAt(Math.floor(Math.random() * possible.length));
}
res.send(slug);
};
module.exports = BudgetController;
===================
//app.js
var express = require('express');
var app = express();
app.use(express.bodyParser());
// models
var Budget = require('./models/budget');
// controllers
var BudgetController = require('./controllers/budget');
var budgetCtrl = new BudgetController(Budget);
// routes
app.get('/budgets',budgetCtrl.generateSlug);
app.listen(process.env.PORT || 4730);
If I manually instantiate the model/controller in the node repl, the generateSlug method works fine. If I restructure my code so that the BudgetController is a function that returns an object {} with methods, that seems to work fine. Is there some issue with my use of prototype/new ?
express takes functions and invokes them without a preceding object, so if you want to use an object method bound to a specific this as an express route handler function, you need to bind it:
app.get('/budgets', budgetCtrl.generateSlug.bind(budgetCtrl));

Resources