combining functionality of two Node servers with different initial set up - javascript

I have two node servers and I need to combine them so one server has the functionality of both. They were set up a little differently and I'm not sure how to resolve it.
The first server has the require statements at the top, routes in the middle and creates the server at the bottom like this:
var express = require('express');
var routes = require('./routes');
etc..
// middleware
// routes
http.createServer(app, function(req, res){
// get files
// check for errors
}).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
The second one looks like this:
var express = require('express')
, app = express()
, server = app.listen(80)
, io = require('socket.io').listen(server)
, fs = require('fs')
var arr= [];
app.get('/aRoute', function(req, res) {
res.writeHead(200);
var data = {
// parse query string
};
arr.push(data);
io.sockets.emit('update', data);
res.end("OK");
});
app.get('/someOutput', function(req, res) {
res.writeHead(200);
res.end(JSON.stringify(footData));
});
io.sockets.on('connection', function (socket) {
});
I cut pasted part of it so now the first server script looks (roughly) like this.
// All imports
var express = require('express');
var routes = require('./routes');
var mongoose = require('mongoose');
var user = require('./routes/user');
var http = require('http');
var path = require('path');
var fs = require('fs');
var multer = require('multer');
var connect = require('connect');
var methodOverride = require('method-override');
var io = require('socket.io');
// middleware
// routes
// trying to make this a route
var arr= [];
app.get('/aRoute', function(req, res) {
res.writeHead(200);
var data = {
// parse query string
};
arr.push(data);
io.sockets.emit('update', data);
res.end("OK");
});
app.get('/someOutput', function(req, res) {
res.writeHead(200);
res.end(JSON.stringify(footData));
});
// THIS GIVES ME ERRORS RIGHT HERE
io.sockets.on('connection', function (socket) {
});
http.createServer(app, function(req, res){
// get files
// check for errors
}).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Combining the two scripts has resulted in an error listed below at the line listed below.
io.sockets.on('connection', function (socket) {
^
TypeError: Cannot call method 'on' of undefined:
// THIS GIVES ME ERRORS RIGHT HERE
io.sockets.on('connection', function (socket) {
});
I don't understand why I'm getting this error after changing the two require statements and moving the server creation and listening to the bottom of the server. Does anyone know how I can fix this?

You're requiring socket.io, which has a .listen method, not an .on method. Once you call .listen, you'll get back an object that has the .on method you're trying to use.
io = require('socket.io').listen(server);
(You're also missing server, which is created in the second script by calling express().listen(somePortNumberLike80)
You can't just copy and paste code and expect it to work, really.

Related

Pass a parameter to another JavaScript and run the script

Send a parameter(URL) from another script through recursion to this script.
var express = require('express');
var request = require('request');
var cheerio = require('cheerio');
var mongodb = require('mongodb');
var app = express();
var MongoClient = mongodb.MongoClient;
// Connection URL. This is where your mongodb server is running.
var murl = 'mongodb://localhost:27017/getData';
url = '';
app.get('/getData', function(req, res){
firstCall(req,res)
//console.log("cookie",req.cookies);
})
var firstCall = function(req, res, data){
console.log("URL: ", url);
res.send('Check your console!');
}
app.listen('3000')
console.log('Magic happens on port 3000');
module.exports = function(app) {
app.get('/getData', function() {});
};
I want this code to act as backbone or logic board. And some other file should be able to trigger this logic board file by adding the URL to this file.
Like we pass parameters to function to call. How do I do it here.

Node.js Socket.io socket.brodcast is undefined

brodcast.emit to send a message to all without socket, and when I do that the node instance crashes and says that socket.brodcast is undefined .
here is my node code:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('public'));
io.on('connection', function(socket){
socket.on("newChild",childData =>{
var newChildID = mainData.newChild(childData.fatherID,childData.data, childData.type);
socket.emit("newChildID",{ "newId" : newChildID,"old" : childData.localID});
socket.brodcast.emit("newChild",maindata.getDataPoint(newChildID));
});
});
when I emit "newChild" from the client the server crashes and say that socket.brodcast is undefined
The important part is to get socket.brodcast.emit , so do I use the API wrong?
when I googled after it I found this: Send response to all clients except sender (Socket.io)
In this thread I found this example:
socket.on('cursor', function(data) {
socket.broadcast.emit('msg', data);
});
And its seams to be the same as i do.
your code contains a typo for starters...
socket.brodcast.emit("newChild",maindata.getDataPoint(newChildID));
should be
socket.broadcast.emit("newChild",maindata.getDataPoint(newChildID));

Node.js: Using Socket.io in an express.js route to send message to a specific client

I have made a very casual commenting system, and now I want to add replies. So, when someone posts a reply on someone else's comment, that user must be notified that someone replied to their comment. In order to do that, when the replier clicks the reply button an AJAX post request is made to the server, the server then needs to get the id of the first commenter and send them a response text using socket.io (socket.io is not required to be used if there is another way to send the reply text with another module or express itself). This is my code so far:
app.post('/reply', function(req, res){
var commenterId = req.body.userId; // this is the id of the original commenter, not the replier
User.findOne({'_id':commenterId}, function(err, user){
user.send({'replied': req.user._id}); // this is what I need to do, and
//I don't know if this specific code works and that's why I'm asking if there is a way to do it with socket.io,
// io.to(socketId).emit('reply', 'some reply text here...'); // but if I do this I don't know how to get the socketId!
//Is there even a way to do this? Maybe with another module,
//or some express function I don't know about? And if it is done with express how would
//the client side code, look like? Thank you!
});
res.end();
});
//app.js file
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var routes = require('./routes/routes')(io);
app.use('/', routes);
//router file
var express = require('express');
var router = express.Router();
var _socket = null;
//list of socket users.once they logout delete the socket by
//delete users[_socket.userid];
var users = {};
var returnRouter = function(io) {
io.sockets.on('connection', function (socket) {
//now _Socket is available inside routes
_socket = socket;
});
router.post('/login', function(req, res) {
//authentication logic
User.findOne({'email': req.body.email}, function (err, user) {
//userid must be unique
_socket.userId= user.userId
//set session variable to store id of the user
req.session.userId = user.userId;
//now every user has a socket associated with their id
users[_socket.userId] = _socket;
});
});
router.post('/reply', function (req, res) {
var commenterId = req.body.userId;
User.findOne({'_id': commenterId}, function (err, user) {
// you can get the id of the logged in user that is the creator
//of the original post from req.session.userId
//if you have implemented session store
//the commenter user object is obtained from findOne method
users[req.session.userId].emit('notification', {
notification: user.username+' commented on your post'
}});
});
res.end();
});
return router;
};
module.exports = returnRouter;

How to extract zip from client in node

I'm having a node app which needs to get some zip file from client Postman and extract it to a folder in my fileSystem,Im using express I did the following which doesnt work,
what am I missing here?
I've created sample node app to simulate the issue.
var express = require('express');
var upload = require('multer')({ dest: 'uploads/' });
var admZip = require('adm-zip');
var app = express();
app.post('/',upload.single('file'),function(req,res){
debugger;
var zip = new admZip(req.file);
zip.extractAllTo("C://TestFolder//TestPathtoExtract", true);
res.send("unzip");
});
var server = app.listen(3001,function(){
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s',host,port);
})
This is how I use it im postman
If there is other way to do it with different open source this can be great!
I use
https://github.com/cthackers/adm-zip
which can be change to any other library
I've also find this lib but not sure how to use it with express
https://www.npmjs.com/package/decompress-zip
Thanks!
This is the set up I did for Postman, first this is my form-data body
Now in the header I left in blank after trying to set multipart/form-data manually and utterly failed, so no header here.
Here I did a pair of console.log, one of req.headers to be sure of Postman sending the right multipart/form-data and another of req.file
And well the output seems to be fine
Edit: the code.
var express = require('express');
var upload = require('multer')({
dest: 'uploads/'
});
var admZip = require('adm-zip');
var app = express();
app.post('/', upload.single('file'), function(req, res) {
console.log('%c > req.headers test.js [9] <=================================', 'color:blue;', req.headers);
debugger;
console.log('%c > req.file test.js [10] <=================================', 'color:blue;', req.file);
//instead of just req.file I use req.file.path as admzip needs the actual file path
var zip = new admZip(req.file.path);
zip.extractAllTo("/Users/myuser/Desktop/ext", true);
res.send("unzip");
});
var server = app.listen(3001, function() {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
You need to pass filename as argument.
Use req.file.path
var zip = new admZip(req.file.path);

Node JS server quit sending files all of a sudden

This was working exactly as it is 2 days ago, I come back to it today, and when I connect from anything other than localhost(including putting IP in address bar instead of the word "localhost", it's just a white page with no error. Here's the code, it's pretty short, so I don't really know where the issue is.
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('public'));
app.get('/', function(req, res)
{
res.sendFile();
});
io.on('connection', function(socket)
{
socket.on('shipID', function(data)
{
socket.broadcast.emit('shipID', data);
});
socket.on('requestID', function()
{
socket.broadcast.emit('requestID');
});
socket.on('move', function(data)
{
socket.broadcast.emit('move', data);
});
});
http.listen(80, function()
{
console.log('listening on localhost:80');
});
As a side note, making that block of code ^ in this text box was obnoxious, is there an easier way to do it other than pressing space 4x at the beginning of each line?

Categories

Resources