Cant start my server when moving everything to 1 file - javascript

at the moment I have an app.js file and a server.js file. The server runs fine when I run 'node app.js' in CMD but I'm trying to put everything in the server.js file.
App.js:
var Server = require('./server.js').Server;
var server = new Server();
server.initialise(8080);
Server.js:
var express = require('express');
var http = require('http');
var events = require('events');
var io = require('socket.io');
var app = express();
exports.Server = Server = function() {
this.userId = 1;
};
Server.prototype.initialise = function(port) {
this.server = http.createServer(app);
app.use(express.static('public'));
this.server.listen(port);
this.startSockets();
this.em = new events();
console.log('Server running on port: ' + port);
};
So I've tried moving the last 2 lines of app.js to the server but I'm getting the error that Server isnt a constructer. I've tried
var Server = this;
I've also tried
this.initialise(8080);
Nothing seems to work

Related

Call a function from module.exports and give value to its parameter

I am building NodeJS code that listens to requests from specific ports and returns a response to it, here is the main code:
module.exports = function (port) {
var fs = require("fs");
var path = require("path");
var express = require('express');
var vhost = require('vhost');
var https = require('https');
var http = require('http');
var bodyParser = require("body-parser");
var normalizedPath = require("path").join(__dirname, "../BlazeData/ssl/");
var options = {
key: fs.readFileSync(normalizedPath + 'spring14.key'),
cert: fs.readFileSync(normalizedPath + 'spring14.cert'),
};
var app = express();
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var normalizedPath = path.join(__dirname, "../WebServices");
fs.readdirSync(normalizedPath).forEach(function(file) {
if (file.indexOf('.js') != -1) {
var url = file.substring(0, file.length - 3);
app.use(vhost(url, require(normalizedPath+"/"+file).app));
console.log( 'Registered Service -> %s:%d', url, port );
}
});
if (port == 80) {
var server = http.createServer(app).listen(port, function(){
console.log("Create HTTP WebServices");
console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});
}
if (port == 443) {
var server = https.createServer(options, app).listen(port, function(){
console.log("Create HTTPS WebServices");
console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});
}
}
I have another JS file that is used to run the script above, I use
var https1 = require('./clientAuthServer') to initiate the code from above where clientAuthServer.js is the filename of the main code, however it just skips everything from that file.
How would I call module.exports = function (port) from a separate file and give a value to the parameter "port" which the function is using?
When you require your module it returns a function (the function exported by the module). The function is being assigned to the variable https1, so you simply need to call that function because right now it's just being stored.
The simplest way would be for your require statement to look something like this:
const https1 = require("./clientAuthServer")(parameter);
Where parameter is just whatever value you want to pass to the function.

Configuring socket.io for node.js application

I have a few questions about configuring socket.io for my node.js application.
When requiring var socket = require('socket.io')( /* HERE */ ), do I need to input the port my server listens where the /* HERE */ is at?
Right below the above line, I have another require function, for a .js file that contains a few constants and a function (see below). When I try to refer to 'socket' in that file it says it's undefined. But since this line is below the require line for the socket.io middleware seen above, why does it say 'undefined'?
const numbers = '1234'
function asd(req,res,next) {
socket.emit('a')
}
module.exports = {
asd
}
For configuring client-side socket.io, I added this line:
var socket = io.connect('https://mydomain')
Do I need to say 'mydomain:port' or is 'mydomain' enough?
This is how you use socket.io
var http = require('http');
var express = require('express');
var path = require('path');
var app = http.createServer();
var io = require('socket.io')(app);
var port = 8081;
io.on('connection', function(socket){
socket.on('event1', function (data) {
console.log(data);
socket.emit('event2', { msg: 'delivered' });
});
});
app.listen(port);
Answer to your second question
Yes, you will need to specify the port you are using
<script src="socket.io.js"></script>
<script>
var socket = new io.Socket();
socket.connect('https://mydomain:8081')
socket.on('your_event',function() {
console.log('your_event receivid from the server');
});
</script>
Here socket will connect to port 8081
This is a simple server side code
var http = require('http');
var io = require('socket.io');
var port = 8081;
// Start the server at port 8081
var server = http.createServer();
server.listen(port);
var socket = io.listen(server);
// example listener
socket.on('event_2', function(client){
console.log('event_2 received');
});
// example emitter
socket.emit('event_1', { hello: 'world' });

How to deploy on windows server : Kurento one to many broadcast

Introduction
I have cloned the project from this git link here
App is running on localhost fine.I am willing to deploy this demo project on windows server where it will run on https://localhost:8443. I have no idea how to deploy this specific demo project, although i have successfully deployed another simple node application on iis.
What can be causing problem, i think from script server.js
var path = require('path');
var url = require('url');
var express = require('express');
var minimist = require('minimist');
var ws = require('ws');
var kurento = require('kurento-client');
var fs = require('fs');
var https = require('https');
var argv = minimist(process.argv.slice(2), {
default: {
as_uri: 'https://localhost:8443/',
ws_uri: 'ws://93.104.213.28:8888/kurento'
}
});
var options =
{
key: fs.readFileSync('keys/server.key'),
cert: fs.readFileSync('keys/server.crt')
};
var app = express();
/*
* Definition of global variables.
*/
var idCounter = 0;
var candidatesQueue = {};
var kurentoClient = null;
var presenter = null;
var viewers = [];
var noPresenterMessage = 'No active presenter. Try again later...';
/*
* Server startup
*/
var asUrl = url.parse(argv.as_uri);
var port = asUrl.port;
var server = https.createServer(options, app).listen(port, function() {
console.log('Kurento Tutorial started');
console.log('Open ' + url.format(asUrl) + ' with a WebRTC capable browser');
});
var wss = new ws.Server({
server : server,
path : '/one2many'
}); .....other code
I have been trying this for 2 days but no luck.Any expert might help.
Thanks for your time.

Error running socket.io and express-nodejs setup

I was working on nodejs executing python scripts using spawn and socket.io methods. I am getting output on the console. but I am not able to display it on the browser. It is showing error.I have pasted the error below. Can any one please help me in solving this problem. I have got this example from this stackoverflow
Here i am pasting my code: sample.py
import random, time
for x in range(10):
print(str(random.randint(23,28))+" C")
time.sleep(random.uniform(0.4,5))
index.js
var express = require("express");
var path = require('path');
var bodyParser = require('body-parser');
var fs = require('fs');
var spawn = require('child_process').spawn;
var http = require('http').Server(app);
var io = require('socket.io')(http);
var app = express();
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.post('/showtemp',function(req,res){
var pathtoScript = spawn('python', ["../External_scripts/sample.py"]);
pathtoScript.stdout.on('data', function (output) {
var val = String(output);
console.log(val);
io.sockets.emit('response', { data: val});
});
})
var server = app.listen(8082,'0.0.0.0', function () {
var port = server.address().port
console.log("App is listening at %s", port)
});
And index.html page
<!doctype html>
<html>
<head>
<title>Live temperature</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<div id="liveTemp">Loading...</div>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
var socket = io();
socket.on('response',function(msg){
console.log("msg");
$('#liveTemp').html(msg.data);
})
});
</script>
</body>
</html>
I am getting this error
GET http://localhost:8082/socket.io/?EIO=3&transport=polling&t=LQSVrTN 404 (Not Found)
GET http://localhost:8082/socket.io/?EIO=3&transport=polling&t=LQSVrTN 404 (Not Found)
You haven't started a web server anywhere or hooked socket.io to it. There are several different ways to do this, but here's one that works:
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
Note: You must see a server.listen() (or equivalent) somewhere. And, you need to pass the server to socket.io so it can hook into it.
You can also do this where you don't directly need to load the http module yourself:
var express = require('express');
var app = express();
var server = app.listen(80);
var io = require('socket.io')(server);
socket.io documentation for several different options here.

scoket.io is not found when listening to different port than server

I have set up a server in node.js using socket.io and epxress.
When I set it up as shown below, it works like charm (now it's listening on 8080).
var express = require("express");
var http = require("http");
var io = require("socket.io");
var app = express();
var server = http.createServer(app).listen(port, host);
var scoketIO = io.listen(server);
But I need it to listen to different port, and if I try eg. 8000
var app = express();
var server = http.createServer(app).listen(port, host);
var scoketIO = io.listen(8000);
I get the following error:
GET http://10.0.33.34:8080/socket.io/socket.io.js 404 (Not Found). Can anybody please help me?
var express = require("express");
var http = require("http");
var io = require("socket.io");
var app = express();
var port = 8000;
var server = http.createServer(app).listen(port, host);
var scoketIO = io.listen(server);
Above code is not tested but most likely it will not fail. Pass port value to listen method of http.createServer(app).
var express = require('express')
http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);
//Code needs to be in this order
and check in the script that the port is 8000
<script src=""></script>
Do you include the script in you html ?
Maybe change the include to the port 8000.
<script src="http://10.0.33.34:8000/socket.io/"></script>

Categories