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(){
...
})
}
Related
I am new to SocketIO, I have referred many blogs and documentation for socket and everywhere we first need to create an HTTP server and then attach the socket to it like this -
var app = express();
var httpServer = http.createServer(app);
var io = socketio.listen(httpServer);
What does the second line mean? why are we creating one extra HTTP server while express(web framework) is already defined?
Because I never created a new HTTP instance for my RESTful application, I simply listened to express instance like this -
var express = require('express');
var app = express();
app.listen(8000);
Thanks in advance!
If you want socket.io to run on the same port as your web server, then you use the same server instance. If you want socket.io to run on a different port, then you create a new server instance on that port just for socket.io to use.
Socket.io works just fine using the same port and server instance as Express so unless you have a specific reason to run it on a different port, this is the usual way one would configure it.
Some code examples for socket.io show it in isolation by itself and thus they have to create an http server for it to use.
When using Express, you can get the server instance like this:
const express = require('express');
const socketio = require('socket.io');
const app = express();
const server = app.listen(8000);
const io = socketio(server);
My goal is this: JS but server-side. My solution, the obvious, node.js. I've used node.js quiet a bit. Mainly for an application, not a web server. The only reason I need to do server-side JS is that I need to use a library that connects to the Discord API. So I have a little test .js file with my node.js in it. It just prints text if it works. Basic. What I need it to do is whenever someone goes to https://example.com/something, it runs the node.js script and if the script ends up with printing "hello", then https://example.com/something will say "hello".
I've done some research on this, I've found ways to deploy a node.js app, which I know how to do. I can't really find anything that I'm looking for though.
You can use express to run a webserver on nodejs
Install express by running "npm install express" in your project folder through command prompt
Create a app.js file with the following code
var express = require('express'); // load the express library
var app = express(); // create an instance of express
var child_process = require('child_process'); //load the child_process module
app.get("/something", function(req, res) { // Setup a router which listens to the site http://localhost/something
child_process.fork("./yourCodeFile.js"); // Launch your code file
});
app.listen(80);
Run node app.js to listen to web connections
Then you put your code into the yourCodeFile.js which has to be be in the same folder as the app.js file, even better you could just write all your code in the app.js code as long as you keep it inside the function inside app.get
You should take a look at cloud-based lambda functions and platforms like AWS Lambda, which run a script in response to an HTTP request. They are relatively new and the architecture used to support this is being called "serverless", which is a simple term, albeit a bit of a misnomer. There are various tools out there to help you build these systems, such as the similarly named Serverless framework, though you can typically still use more traditional server frameworks that you are probably more comfortable with. Either way, you are not responsible for managing any server, including starting it or stopping it.
In terms of constructing a response that you are happy with, you can of course respond with any arbitrary string you want. See the AWS example of a Node.js handler.
exports.myHandler = function(event, context, callback) {
callback(null, "Hello, world!");
}
Lambda functions can also return binary data and work well with static storage systems like Amazon S3. For example, the function can be run in response to the creation of static assets.
Your code should look like this:
const http = require('http');
const url = require('url');
const hostname = '127.0.0.1';
const port = 3000;
const server = http.createServer((req, res) => {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
const pathName =url.parse(req.url).pathname;
if (pathName == '/something') {
res.end('Hello World\n');
} else {
res.end('Please visit /something \n');
}
});
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});
You should run your file with node youfile.js And when you do curl http://127.0.0.1:3000 you will see
Please visit /something
But when you do curl http://127.0.0.1:3000/something you will see
Hello World
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)
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.
Please be gentle with me. I'm new to async coding and have been thrown headfirst into an intensive project using node to develop and API server. I'm loving it but some things aren't coming naturally.
Our project is built using express js. We have a file, server.js where we instantiate an express server which in turn instantiates our router and so on. I need to integration test this now (partially) complete server. Normally what I do is from the command line run '%node server.js' and then using either python requests or curl make requests and check the responses.
Now I've been tasked with writing a unit and integration test suite so that we can automate our testing going forward. I've been using mocha and now am trying to use supertest for the integration testing. The problem is that supertest expects a server object which it then applies tests to however our file that builds our server object doesn't return anything. I don't want to modify that file so I am stumped as to how to access the server object to use for testing.
My server file looks (in part) like this:
var express = require('express')
var app = express();
// Express Configuration
app.use(express.favicon()); //handles favicon request, which keeps it out of the log when using a browser :)
app.use(express.bodyParser()); //slurps up the body in chunks the node.js way :)
// ...and so on
and my mocha test file looks like this
var request = require('supertest')
, app = require('../server.js')
, assert = require("assert");
describe('POST /', function(){
it('should fail bad img_uri', function(done){
request(app)
.post('/')
.send({
'img_uri' : 'foobar'
})
.expect(500)
.end(function(err, res){
console.dir(err)
console.dir(res)
done();
})
})
})
when I run this test I get a complaint about the app object not having a method named address. My question is, is there a way I can require/call the server.js file so that the app object will be in scope? Or am I going about this wrong. I also played around a little bit with using http.js to make calls directly to the server but didn't have luck that way either. Thanks!
You need to export the app object in server.js:
var app = express();
module.exports = app;
...