Using socket.io in multi files - javascript

I am using Node.js Express with socket.io.
//app.js
var server = http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
var io = require('socket.io').listen(server,{'log level': 1});
and if I want to do "io.sockets.emit" only for people watching index page which is provided by index.js how can I call "io.sockets.emit" in index.js other than using "require" for app.js(main file)?
I've googled about it though I couldn't find any sample source code which use socket.io in multiple files.

If your backend is separated in several module files like index.js, it's possible to pass variables to modules upon initialization.
Try importing index.js after initializing socket.io, and pass io to the index.js module being imported:
require('./index.js')(io);
See also this answer.

Related

Proper way of emitting an event from a function - Node JS - Socket.io

Assume that I have two files.
server.js
test.js
server.js have all the initialization codes in place (Mongoose, Express..etc). It also has the below code:
const io = require('socket.io')(server);
In my test.js file, I have something related to mqtt. It is irrelevant, however, please understand that I don't have any variable access in there (req, app). Because that file isn't part of the route or anything.
It is included in server.js as:
require('test.js');
I am not getting into any details of MQTT or how it works. Consider that one or more functions inside test.js is running on a specific time. So, when ever that happens, how can I emit an event using socket.io from the test.js file?
My client side dashboard is ready to receive the event. I am just confused how to design the system, especially how to access the io variable which exist in server.js file.
As mentioned already just export a function from test.js that takes io as a parameter:
module.exports = function test(io) {
io.on("connection", socket => {
socket.emit("greeting", "hello world!");
});
};
From your server.js you just have to pass in the argument:
require("./test.js")(io);

browserify Wordnet thesaurus

I am using a thesaurus API (altervista) for my JavaScript web app but I want to be able to make lots of synonym requests without worrying about API quotas, etc. I want to self-host a thesaurus on my web host and I would like to send words and receive their synonyms from JavaScript in the browser.
As research I tried node, and within node I was able to get synonyms with these packages:
"natural" and "wordnet-magic"
so then I tried to browserify "natural" and "wordnet-magic" node packages. On attempting to browserify "natural":
"Error: Cannot find module 'lapack'"
"lapack seems to be a native OS-dependent shared library, so it can't be browserified." https://github.com/moos/wordpos/issues/9
Also I had no luck browserifying "wordnet-magic":
"Uncaught TypeError: Cannot read property '_ansicursor' of undefined"
Possibly related (since sqlite3 is in my wordnet-magic packages), instances of same error reported here but still unresolved: https://github.com/mapbox/node-sqlite3/issues/512
My second choice would be a PHP solution should it be impossible in JavaScript. It does not have to use Browserify or Wordnet, but Wordnet would be such an amazing thing to have in the browser. Thanks.
Okay I can get synonyms in the browser (thanks to Stuart Watt):
I followed instructions to setup a javascript wordnet app here:
https://github.com/morungos/wordnet
then did
npm install express
and then ran this code with node:
var express = require('express');
var app = express();
var WordNet = require('node-wordnet');
var wordnet = new WordNet();
app.get('/lookup', function(req, res) {
wordnet.lookup(req.query.word, function(results) {
res.send(results);
});
});
app.listen(3000, function() {
console.log('Example app listening on port 3000!');
});
and you can then see wordnet in your browser, e.g.
http://localhost:3000/lookup?word=wind
It's visible, it works, and to consume it in your html, see this answer:
https://stackoverflow.com/a/36526208/5350539

How to build socket io server in different file except app.js

I am pretty new to node.js and now I am doing a project on building a website on node.js. Sorry if my question is very naive.
I am using express framework.
My app.js is listening at port (3000).
In my route.js, I got some data from calling some API. I want to display the data to my datapoint.jade file. And because I want to draw those datapoint I have to embed a javascript file in jade. I want to use socket.io to achieve this sending and receiving data.
However, all the examples to construct socket is in app.js. I get data in router.js(in one of its callback function). app.js require router.js.
How can I send data from route.js to app.js and then send out to client side.
Could you please guide me some related and useful information? Or my design would not work at all?
A common paradigm is to pass any dependencies to your child modules:
// app.js
var socket = require('socket.io');
var app = require('express')();
var routes = require('./routes.js')(app, socket);
app.listen();
// routes.js
module.exports = function(app, socket){
var routes = {};
app.use('/', routes.handleIndex)
socket.on('connection', function(){
...
})
}

Socket.io in Express routes file

I'm working on a project which consists in creating a game of the goose like. In order to do that, I'm using Node.js, Express, jade and now Socket.io. But I encounter some trouble, like, in example, to share the position of one client to the other client. Because my variable position is in a function in index.js and I don't know how I can use Socket.io in a route file. I try some things, but nothing works.
On internet, I've seen some people who say that there is no-sense to use Socket.io in an express route file. So how can I do that ?
In my index.js I've that :
exports.deplacement = function(io)
{
return function(req,res)
{
//[...]
io.sockets.on('connection', function(socket)
{
socket.broadcast.emit('position', space);
});
res.render('moteur' //[...]);
}
}
And in my moteur.jade I've done this :
script(src="/socket.io/socket.io.js")
script.
var socket = io.connect('http://localhost:3000');
socket.on('position ', function(space) {
alert(space);
})
First of all, I'm not sure what your question exactly means, but if it is what I think it is then I think what you mean by using socket.io in a route file is to be able to include the client side javascript lib provided with socket.io module of Node.
In order to do that, you have to allow the socket.io module to listen to server. This works like a middle-ware itself. Everything has to go through socket.io first before they are routed to the server. So, when you request the client side lib, it is uploaded to the client.
var express = require('express')
, routes = require('./routes')
, http = require('http');
var app = express();
var server = app.listen(3000);
var io = require('socket.io').listen(server)

Where is the Socket.IO client-side .js file located?

I am trying to get socket.io (Node library) to work.
I have the server-side js working, and it is listening. The socket.io website states simply:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
This is nice, however, what JS file am I importing!?!
I went into the node_modules directory, where I installed socket.io through npm, and inside socket.io/lib/ is socket.io.js file. However, this is server-side (uses the phrase require(), which errors on the client).
I have spent an hour looking around and I can't get any client .js file to work.
What am I missing?
I managed to eventually answer this for myself.
The socket.io getting started page isn't clear on this, but I found that the server side of socket.io automatically hosts the .js file on starting node, in the directory specified in the documentation:
"/socket.io/socket.io.js"
So you literally just point to this url regardless of your web app structure, and it works.
I would suggest checking if your node_modules directory is at the top level of your app directory. Also, I do believe you need to specify a port number; you should write something like var socket = io.connect('http://localhost:1337');, where the port number is 1337.
If you did npm install then the client socket.io file is located at node_modules/socket.io-client/dist/socket.io.js
Source: Socket get-started page
The client is available in a few ways:
supplied by the socket.io server at /socket.io/socket.io.js
included via webpack as the module socket.io-client
via the official CDN https://cdnjs.cloudflare.com/ajax/libs/socket.io/<version>/socket.io.js
For the first one, the server can be configured in a couple of ways:
// standalone
var io = require('socket.io')(port);
// with existing server from e.g. http.createServer or app.listen
var io = require('socket.io')(server);

Categories

Resources