I'm new to Node and async programming. I'm building a website in which I have to fetch some data from external websites and show it to client(AngularJS Client).
What I want to do is that whenever my server starts, it should fetch data from the external websites and place it in DB.
I have following code in my server.js file:
var express = require('express'),
app = express(),
abc = require('./server/controllers/abc');
app.listen(3000, function () {
console.log('I\'m listening...');
});
app.on('listening', function(){
abc.visitPages;
});
and following snippet in abc.js:
module.exports.visitPages = function () {
console.log('Going to visitPages');
}
my server works fine but it does not go to the visitPages() function in abc.js any help in this regard would be very kind.
thanks in advance.
You need to make sure you're actually running the function. Unlike some other languages, you must provide the parentheses to signify that the function should be invoked in javascript.
Use abc.visitPages() inside your listen callback.
Also, I'm not sure app.on('listener') will ever fire. Looks like express doesn't support it. I would move the method call into your app.listen() callback instead.
app.listen(3000, function () {
console.log('I\'m listening...');
abc.visitPages();
});
You can directly call you function .
var express = require('express'),
app = express(),
abc = require('./server/controllers/abc');
abc.visitPages();
app.listen(3000, function () {
console.log('I\'m listening...');
call_my_function();
});
Here's what you want, note that there is no event called listening, you have to emit it
var express = require('express'),
app = express(),
abc = require('./server/controllers/abc');
app.listen(3000, function() {
console.log('I\'m listening...');
app.emit('listening'); // <-- just emit this event
});
app.on('listening', function() {
abc.visitPages(); // <-- call function
});
//alternate
app.on('listening', abc.visitPages);
Related
Let's say the entry point of my app is app.js
I want to create a socket connect when the app runs and then export it to other files throughout the application.
Here is a bit of example code
const express = require('express');
const WebSocket = require('ws');
const app = express();
app.use(allTheMiddleWares);
app.listen(PORT, () => {
console.log('started app');
}
const socket = new WebSocket.Server({server: app});
module.exports = socket;
Then when I try to access the export from app.js I always end up with an empty object.
I have also tried exporting functions:
module.exports = {
test: () => console.log("why don't I work")
}
However this also returns an empty object.
Thanks in advance for the help.
As a temporary work around to access the socket globally I have set process.WebSocket = new WebSocket.Server({server: app});. I would like to know if there are any glaring issues with this.
Making my comment into an answer since it was your solution.
You are not passing a server to the WebSocket constructor. app is a request handler. It is not a server. app.listen() returns a newly created server object.
Change your code from this:
app.listen(PORT, () => {
console.log('started app');
}
const socket = new WebSocket.Server({server: app});
to this:
const server = app.listen(PORT, () => {
console.log('started app');
}
const socket = new WebSocket.Server({server: server});
See code for app.listen() here.
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
See doc for app.listen() here.
The app.listen() method returns an http.Server object and (for HTTP) is a convenience method for the following:
I am on the process of building a chat application with nodejs, reactjs mongo and socket.io.My chat app consists of both one to one and group chats.I have built a schema for group chat and i am inserting group names along with its members and their chats in the table.Since im a beginner towards socket.io, I dont know where to put the socket logic that needs to be fired after the db post operation.Can some one suggest any examples for me?
Update your code accordingly:
=> server.js file
// Declare socket.io
const io = require('socket.io')(server);
// Add middleware to set socket.io in
app.use((req, res, next)=>{ res.locals['socketio'] = io; next(); });
=> In your controller file
// Get the value of socket.io
module.exports = your_function_name = (req, res) => {
const io = res.locals['socketio']
// Use io when you need.
});
Hope this solves your query.
You can separate you socket related code by following way :
==>app.js
var express = require('express');
var socket = require('./socketServer');
var app = express();
var server = app.listen((config.node_port || 3000), function () {
console.log('Listening on port ' + (config.node_port || 3000) + '...');
});
socket.socketStartUp(server);
module.exports = app;
==>socketServer.js
var io = require('socket.io')();
var socketFunction = {}
socketFunction.socketStartUp = function (server) {
io.attach(server);
io.on('connection', function (socket) {
console.log("New user is connected with socket:", socket.id);
})
}
module.exports = socketFunction;
You can also check node API startup code with socket functionality in below link:
Node API Start up
Hope this answer is helpful to you
I'm making some single page web application with Node.js, Express and Socket.io. I want to display how works are going to browser. In IDE, There is console, so I can check program process in console window. Like, I want to show these process to browser. All I want to is just 'emit'.
When I use socket.io in app.js file, there is no problem. but this is limited for me. I want to display many sentences in realtime as running. How can I use socket.io in not only app.js but controller.js? I red Use socket.io in controllers this article, but I can't understand. Please help me with a simple solution.
app.js
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
module.exports.io = io;
...
controller.js
var io = require('./app').io;
// some task
console.log('Task is done!'); // it would be seen in console window
io.sockets.emit('Task is done!'); // Also I want to display it to broswer
Result (error)
TypeError: Cannot read property 'sockets' of undefined
Edit 2---
Follwoing Ashley B's comments, I coded like this.
controller.js
module.exports.respond = function(socket_io) {
socket_io.emit('news', 'This is message from controller');
};
app.js
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var controller = require('./controller');
io.sockets.on('connection', controller.respond );
It works well, But what I wonder is... When I want to several socket_emit, What Should I do? Should I call everytime? If you don't understand. see below :
//first task is done
module.exports.respond = function(socket_io) {
socket_io.emit('news', 'First task is done!');
};
//second task is done
module.exports.respond = function(socket_io) {
socket_io.emit('news', 'Second task is done!');
};
//third task is done
module.exports.respond = function(socket_io) {
socket_io.emit('news', 'Third task is done!');
};
But It is wrong way, right? only last api is implemented in app.js. There are a lot of console.log in my controller, I want to convert it to socket.emit How can I do this?
I have worked on this using socket.io and nodejs events. The idea is to handle the emission of the socket only from the app.js, and emit nodejs events from controllers, which will be captured in app.js and then issued by the socket.
app.js
const app = express();
const http = require('http');
const server = http.createServer(app);
const io = require('socket.io')(server);
const events = require('events');
io.on('connection', function(socket) {
console.log("Someone has connected");
var eventEmitter = new events.EventEmitter();
eventEmitter.on("newEvent", (msg) => { // occurs when an event is thrown
socket.emit("news", msg);
});
exports.emitter = eventEmitter; // to use the same instance
});
myController.js
const app = require('../app');
.....
if (app.emitter) // Checking that the event is being received, it is only received if there is someone connected to the socket
app.emitter.emit("newEvent", "First task is done!");
.....
if (app.emitter)
app.emitter.emit("newEvent", "Second task is done!");
I am not able to run socket.io code in node.js, console.log() is also not displaying when running the code. Below is the code.
app.js
var express = require('express');
var http = require('http');
var app = express();
app.set('port', process.env.PORT || 3000);
app.post('/testStream',test.testStream);
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
module.exports.appServer = server;
and I have created a test.js file where I am accessing this exported variable appServer.
var server = require('../app.js');
exports.testStream = function(req,res){
var io = require('socket.io').listen(server.appServer);
io.on('connection',function(socket){
console.log("in socket");
fs.readFile('E:/temp/testimg.png',function(err,buf){
socket.emit('image',{image: true,buffer: buf});
console.log("test image");
});
})
}
when the code runs it stucks and not showing the console.logs(). What I am doing wrong over here. Any help is very much appreciated.
I would suggest following the code structure as suggested in socket.io docs.
Also, you should not be calling io.listen or io.on('connection') inside your testStream express middleware. These are things you should only be doing once, and ideally they should happen during startup, inside app.js and not in reaction to a POST request. In fact, I'm not sure what the purpose of your testStream middleware is, its not even returning any response (eg res.end())
If you want to handle socket connections in a separate module you can, but instead of exporting your app's server the way you are, try passing the io instance as variable to your submodule. In short, try this:
app.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var test = require('./test')(io);
app.set('port', process.env.PORT || 3000);
server.listen(app.get('port'), function() {
console.log('Express server listening on port ' + app.get('port'));
});
test.js
module.exports = function(io) {
io.on('connection', function(socket) {
console.log("in socket");
fs.readFile('E:/temp/testimg.png', function(err, buf) {
socket.emit('image', {
image: true,
buffer: buf
});
console.log("test image");
});
});
};
I've always been a bit of a Perl/PHP sorta guy, but I fancy a change and Node JS seems like the right place for me to go next.
I've watched a good few hours of tutorials on YouTube and read some posts on here - but I have come up a bit stuck.
I'd like to include socket.io in my express-generated application (v4.10.6).
At the same time though, I don't really want to include the socket.on(...) statements in one file - i'd much rather split it out like you would with a route.
Given that the express-generated app is started in bin/www, i'm confused as to where I need to require('socket.io') and point all the 'on' events to.
This post on stackoverflow, I think may answer my question - but it suggests all the socket handlers are in the ./sockets/base.js file - and I am confused by the Gofilord's response to the answer.
Please forgive my ignorance here - this is all a bit alien to me at the moment, and thank you, as always for taking the time to read this and your help.
/bin/www
#!/usr/bin/env node
var debug = require('debug')('rhubarb');
var app = require('../app');
app.set('port', process.env.PORT || 1127);
var server = app.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
Its typical to require socket.io in app.js and then to tell your io sever to listen to your application. Using the example you posted, that would look like this:
var debug = require('debug')('rhubarb');
var app = require('../app');
var server = require('http').Server(app);
var io = require('socket.io')(server);
app.set('port', process.env.PORT || 1127);
var server = server.listen(app.get('port'), function() {
debug('Express server listening on port ' + server.address().port);
});
The socketio docs do a really good job of explaining this. Here's an example from their homepage:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Update:
I typically modularize socketio setup by creating a lib called io.js in /lib with something like this:
module.exports = function(server){
var io = require('socket.io')(server);
// catch errors
io.on('error', function(err){
throw err;
})
// Set Socket.io listeners by creating a socket.io middleware
// attachEventlisteners would live in `/controllers`
io.use(attachEventlisteners);
io.on('connection', function (socket) {
// do things
});
return io; // so it can be used in app.js ( if need be )
}
then in app.js i can simply pass the server in when I require it:
var io = require('./lib/io')(server);
You dont need to do any thing further in app.js since everything is setup in /lib/io.js, but if you wanted to you could because the io server is returned.