Node js, how to combine Socket.io with mustache - node.js

Socket.io can be used in the general html page, but it can not be used in the mustache page?
For example:
app.js
var app = express();
app.use(express.static(path.join(__dirname, 'public')));
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'mustache'); // name your templates
app.engine('mustache', require('hogan-middleware').__express);
var routes = require('./routes/index');
app.use('/', routes);
routes\index.js
var express = require('express');
var router = express.Router();
var app = express();
var server = require('http').Server(app);
var io = require('socket.io').listen(server);
var request = require('request');
var serialport = require('serialport');
var Serialport = serialport;
router.get('/machine_mode', function(req, res, next) {
res.render('machine_mode', { title: 'test' });
});
io.sockets.on('connection',function(socket){
var str='hello';
io.sockets.emit('view',str);
});
views\test.mustache
<body>
</body>
<script src="/js/jquery-1.9.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($){
var socket = io.connect();
socket.on('str',function(data){
})
});
the test page error:
can not GET
http://localhost:8001/socket.io/socket.io.js

app.js
var express = require('express');
var router = express.Router();
var app = express(); // Brackets Missing
var server = require('http').createServer(app); // Need to do like this
var io = require('socket.io').(server); // Need to pass server
var request = require('request');
var serialport = require('serialport');
var Serialport = serialport;
router.get('/machine_mode', function(req, res, next) {
res.render('machine_mode', { title: 'test' });
});
io.on('connection',function(socket){ // io.socket is not required
var str='hello';
sockets.emit('view',str);
});

Related

Pass data from client to server. Express

i'm little stuck on my express application.
I have a file index.js in routes folder and I want to save the result of mydata
var express = require('express');
var router = express.Router();
router.get('/', token, function(req, res, next) {
var mydata = req.userId
res.render('index', {
title: 'Welcolme',
});
});
module.exports = router;
And, in my other file (which depends on app.js), I would like to get and pass mydata to the server
var app = require('../app');
server.listen(port, function () {
require('../assets/js/server/socket')(server, mydata);
});
(Here is my app.js)
var express = require('express');
var indexRouter = require('./routes/index');
var path = require('path');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'twig');
app.use('/', indexRouter);
module.exports = app;
And the socket file
var io = {};
module.exports = (server, mydata) => {
console.log('Hello : ' , mydata)
io = require('socket.io')(server);
io.on('connection', (socket) => {
console.log('Connected')
});
};
Is there a way to do that?
Thank you :)
Maybe instead of still having this route.get('/') ...
You can let the user enter the data and have it transferred directly through the WebSocket connection.
Example:
//Client-side
//Get the user data somewhere from the HTML page
const userData = document.getElementbyId("some html element's id here").innerHTML;
//Send it to the back end
socket.emit('userData',userData)
//Open a listener to get the data from the back end later
socket.on('processedData',processedData=>{
//Use it in the way you desired.
});
//Server-side
io.on('connection', (socket) => {
console.log('Connected')
socket.on('userData',userData=>{
//Do something here, like validation and stuff
socket.emit('processedData','processedData here')
});
});

Emitting and receiving events with Socket.io

I'm trying to emit an event with socket.io on my Node Js server and receive it client-side but I can't get it to work.
This is my server code:
// require our dependencies
var express = require('express');
var expressLayouts = require('express-ejs-layouts');
var bodyParser = require('body-parser');
var app = express();
var port = 3000;
var server = require("http").Server(app);
var io = require('socket.io')(server);
// use ejs and express layouts
app.set('view engine', 'ejs');
app.use(expressLayouts);
// use body parser
app.use(bodyParser.json({extended : true}));
// route our app
var router = require('./app/routes');
app.use('/', router);
// set static files (css and images, etc) location
app.use(express.static(__dirname + '/public'));
// start the server
app.listen(port, function() {
console.log('app started');
});
This is my routes.js code, where the magic should happen:
module.exports = function(io){
// require express
var express = require('express');
var path = require('path');
// create our router object
var router = express.Router();
// export our router
//module.exports = router;
router.post("/", function(request, response) {
console.log(request.body);
io.emit('getupdate',{hello:'world'});
});
// route for our homepage
router.get('/showevent', function(req, res) {
res.render('pages/showevent',{data:exportage});
});
return router;
}
While this is my client-side script:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('getupdate', function (data) {
console.log(data);
});
</script>
On the routes.js file, to get the "io" variable i wrapped all inside a function.
I can't get the message emitted in case of a POST request on my client.
Could you help me to find the issue here ?
Try this:
// require our dependencies
var express = require('express');
var expressLayouts = require('express-ejs-layouts');
var bodyParser = require('body-parser');
var app = express();
var port = 3000;
var server = app.listen(port);
var io = require('socket.io').listen(server);
I am not sure if you have updated this in your own code, but this snippet should pass io to the router:
// route our app
var router = require('./app/routes')(io);
app.use('/', router);

Node express cannot get static file

This is the picture of my server
https://drive.google.com/file/d/1GA57RyYsc5ik1pSlLhAGtgGjbp_vLFoH/view?usp=sharing
When I go to http://localhost:3000/
I get the error message: Cannot Get/
myserver.js
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use(morgan('dev'))
app.use(express.static('client'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');
Whenever you are trying to visit any url on the browser , then browser makes a GET request to that url, in your case you are not sending any response on the url: "http://localhost:3000/. You can try something like this.
app.route('/*')
.get(function(req, res) {
res.sendFile(path.resolve("./client") + '/index.html'));
});
Check the naming you used, it shows myserver.js instead of server.js as in the picture you uploaded.
Check your routing on line 10 of you code
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
. try this edited codes
server.js
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var lionRouter = require('./server/lions');
var tigerRouter = require('./server/tigers');
app.use(morgan('dev'))
app.use(express.static('client'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');
Express static directory is given client but it is present on parent directory.
So i have resolve this issue with path module and now this will work for you.
// TODO: mount the tigers route with a a new router just for tigers
// exactly like lions below
var express = require('express');
var bodyParser = require('body-parser');
var app = express();
var _ = require('lodash');
var morgan = require('morgan');
var path = require('path')
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use(morgan('dev'))
app.use(express.static(path.join(__dirname, '../client')));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
// this is called mounting. when ever a req comes in for
// '/lion' we want to use this router
app.use('/lions', lionRouter);
app.use(function(err, req, res, next) {
if (err) {
res.status(500).send(error);
}
});
app.listen(3000);
console.log('on port 3000');
Your code works fine after commenting the following three lines of your code:
var lionRouter = require('./lions');
var tigerRouter = require('./tigers');
app.use('/lions', lionRouter);
Check if any error is present in LionsJS.

ExpressJS + Socket.IO Routing

Repeated Question, But i found no perfect answer as a solutions. Please help me to solve this issue.
My App.js
var routes = require('./routes/index');
var users = require('./routes/users');
var media = require('./routes/media');
var widget = require('./routes/widget');
var display = require('./routes/displays');
var device = require('./routes/deviceinfo');
app.use('/', routes);
app.use('/display', display);
var server = http.createServer(app);
var io = require('socket.io')(server);
io.set('transports', ['polling', 'websocket']);
Display Routes: "routes/display.js"
I have code to insert a display, As soon a display is created an event should emit to the list of devices.
Emit should need to write in save success callback Method.
var express = require('express');
var router = express.Router();
router.post('/save', action_save_displays);
function action_save_displays(req, res){
display.save(req,body , function(err , display){
if(!err){
res.json(display);
//io.sockets.emit("displaycreated", display);
}
})
}
module.exports = routes;
How to pass io.sockets.emit in routes/display.js file. really appreciate your guidance. how to send socket object to routes to enable emit event.
You can swap the requires around a bit, and just pass socket.io to the display.js file
var routes = require('./routes/index');
var users = require('./routes/users');
var media = require('./routes/media');
var widget = require('./routes/widget');
var server = http.createServer(app);
var io = require('socket.io')(server);
var display = require('./routes/displays')(io); // here
var device = require('./routes/deviceinfo');
app.use('/', routes);
app.use('/display', display);
io.set('transports', ['polling', 'websocket']);
and get it in the display.js file
var express = require('express');
var router = express.Router();
module.exports = function(io) {
router.post('/save', function(req, res) {
display.save(req.body , function(err, display){
if(!err){
res.json(display);
io.sockets.emit("displaycreated", display);
}
});
});
return router;
}

separate logic from view with route

I'm pretty new to Node and I'm using express.
I'm trying to implement simple file explorer.
enough talking here's some code:
(root dir is /app for this ex.)
my app.js:
var express = require('express');
var fs = require('fs');
var path = require('path');
var ejs = require('ejs');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var explorer = require('./routes/explorer');
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use("/public", express.static(__dirname + '/public'));
app.use('/', explorer);
server.listen(3000,function(){
console.log('Server started on http://localhost:3000');
});
io.on('connection',function(client){
console.log('connection with io established');
});
module.exports.app = app;
module.exports.server = server;
see that I have routing '/' to explorer
and the explorer.js:
var express = require('express');
var router = express.Router();
var fs = require('fs');
router.get('/', function(req, res, next) {
res.render('explorer',{
currentPath : currentPath
});
});
function getUserHome() {
var rawPath = process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
return rawPath;
}
function clicked(){
console.log(getUserHome());
}
the view explorer.ejs:
<div class="clickable">clickme</div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
$('.clickable').click(function(){
socket.emit('clicked');
});
</script>
basically i want to catch the "clicked" emit from the view and trigger the clicked function in the explorer.js. in other words i want the view and the explorer.js talk by socket.io, so the view can talk with the file system.
i tried few way and got bunch of error.
thank you so much!
So you've triggered the event 'clicked' on your client side :
// Client side :
var socket = io.connect('http://localhost:3000');
$('.clickable').click(function(){
socket.emit('clicked');
});
Now, you have to catch it on the server side, in the explorer.js file :
// Server side :
// Instanciate your socket.io on the server side
var io = require('socket.io')(server)
// Listen for a client connection :
io.sockets.on('connection', function(socket){
// Inside the connection, you can now declare each function for each event triggered on the client side
socket.on('clicked', function() {
// This is your callback,
//+ the code in this scope will be executed
//+ only when the event 'clicked' is emitted
cliked();
});
});

Resources