Engine.IO tutorial needed [closed] - node.js

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
Hi I am trying to use Engine.IO.
As stated here on StackOverflow it is supposed to be low level version of Socket.IO. Also it supposed to be better and newer. Also it should give me the ability to easily exchange messages between browser client and Node.js server. Doh.
I read from top to bottom these two pages:
https://github.com/LearnBoost/engine.io
https://github.com/learnboost/engine.io-client
But it does not help, those manuals seem to be written for somebody who already know how to use the technology not for somebody who is trying to learn it. Even the basic parts are missing.
How the client script is supposed to get to the browser?
What is the landing address for the "hello world" I should type in the browser?
Step-by step instruction to got started?
Please help! This is not easy when you try to learn something like that!
This is what the client script supposed to be:
<script src="/path/to/engine.io.js"></script>
<script>
var socket = new eio.Socket('ws://localhost/');
socket.on('open', function () {
socket.on('message', function (data) { });
socket.on('close', function () { });
});
</script>
But now what is that? Index.html? What does it all mean? How to use it?
Now here is the "server" part:
(A) Listening on a port
var engine = require('engine.io')
, server = engine.listen(80)
server.on('connection', function (socket) {
socket.send('utf 8 string');
});
(B) Intercepting requests for a http.Server
var engine = require('engine.io')
, http = require('http').createServer().listen(3000)
, server = engine.attach(http)
server.on('connection', function (socket) {
socket.on('message', function () { });
socket.on('close', function () { });
});
(C) Passing in requests
var engine = require('engine.io')
, server = new engine.Server()
server.on('connection', function (socket) {
socket.send('hi');
});
// …
httpServer.on('upgrade', function (req, socket, head) {
server.handleUpgrade(req, socket, head);
});
httpServer.on('request', function (req, res) {
server.handleRequest(req, res);
});
Why is this broken in three parts? Which one corresponds to the client example? Maybe I sound dumb, but how to get the "hello world" going?

I would suggest you read the following book , it will clear out some of your concerns.
"http://www.nodebeginner.org/".
Then try to make your first NodeJS App just doing what the book says , so that you get a bit the idea behind it.
After that go on and use "socket.io" and create a simple app with the help of this tutorial "http://net.tutsplus.com/tutorials/javascript-ajax/real-time-chat-with-nodejs-socket-io-and-expressjs/".
After that i believe you will not have any questions regarding engine.io and you will be able to go on with your project.
Jumping to engine.io without prior knowledge of "NodeJS" and "socket.io" has a hard learning curve.

Related

How do you save the results of a mongoose query to a variable, so that its value can be used *later* in the code?

I know this question has been asked a few times, but none seem to answer the particular part of using the query results for later.
I also know the problem resides on the fact that queries are asynchronous, and perhaps this is the reason I cannot seem to find a satisfactory answer.
Here's what I'm trying to do:
I have a node project with several sections, each section with different content. These sections have individual properties, which I decided to store in a Model for later use.
So far (and for simplicity sake) I have the following schema:
const SectionSchema = new Schema({
name: String,
description: String
})
const Section = mongoose.model('Sections',SectionSchema)
I'd like to retrieve this data to be used in one of my layouts (a navigation header), so I tried something like this:
const express = require('express')
const app = express()
Section.find().then(function(docs){
app.locals.sections = docs
})
console.log(app.locals.sections) // undefined
This obviously doesn't quite work due to find() being asynchronous, or rather, it does work but the values are populated at a different time. I know that if I do the console.log check inside the function I'd get a result, but that's not the concern, I want to store the data in app.locals so that I could later use it in one of my layouts.
Ideally I'd like to load this data once, before the server begins to listen to requests.
Feel free to correct me if I've made any wrong assumptions, I'm very new to node, so I don't quite know how to approach things quite yet.
Thanks in advance.
EDIT: I should've mentioned I'm using express.
Your node app will likely be comprised of route handlers for http requests. app.locals.section will be undefined if you call it outside of the callback, but it will exist in the route handler.
Let's say you were using something like express or restify:
const app = restify.createServer()
app.get('/', (req, res) => {
return res.json(app.locals.sections)
})
Section.find().then(function(docs){
app.locals.sections = docs
})
console.log(app.locals.section) // is undefined
app.listen(8080-, ()=>{
console.log('Server started 🌎 ',8080)
})
Actually, it might be undefined if the database call took a long time and or a user hit the app super soon after startup. Starting the server in the callback would ensure app.locals.section existed under every scenario:
Section.find().then(function(docs){
app.locals.sections = docs
app.listen(8080-, ()=>{
console.log('Server started 🌎 ',8080)
})
})
You can use async/await within a function to make it seem like you aren't using promises. But you can't use it at the top level of your module. See here: How can I use async/await at the top level?
It really would be fairly idiomatic to do all your app startup in a promise chain. It's a style of coding you are going to see a lot of.
Section.find().then((docs)=>{app.locals.sections = docs})
.then (()=>{/*dosomething with app.locals.sections */})
.then(startServer)
function startServer() {app.listen(8080-, ()=>{
console.log('Server started 🌎 ',8080)
})}

socket.io rooms difference between to and in

I'm trying to get myself acquainted with socket.io and node. https://socket.io/docs/rooms-and-namespaces/
This is my reference.
var socketIO = require('socket.io')(http);
socketIO.on('connection', function(socket) {
socket.join(data.room);})
socketIO.in(users[key].room).emit('newmsg', data);
socketIO.to(users[key].room).emit('newmsg', data);
Here the code with socketIO.in gives output whereas socketIO.to doesn't
But as per their documentation in and to should return the same o/p.
Someone please explain to me the critical difference b/w them.
Right in the socket.io doc:
namespace.in(room)
Synonym of namespace.to(room).
So, .to() and .in() are the same.
And, if you look in the code, you see this:
Namespace.prototype.to =
Namespace.prototype.in = function(name){
if (!~this.rooms.indexOf(name)) this.rooms.push(name);
return this;
};
So, both .to() and .in() run the exact same code so any difference you think you are seeing is not because of the difference between calling .to() or .in(). It must be due to something else. You'd have to show us a reproducible set of code that shows some difference for us to help you debug that.

How to catch messageBack in node.js [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am trying to use messageBack in Bot framework. (The reason is postBack is not supported for MS Teams and imBack shows the system message to the user. I also tried to use invoke but that function is no longer in the botbuilder library)
I found the function messageBack in the library botbuilder, but I dont know how to catch the action once user presses the button.
For imBack I can use this:
bot.dialog('catchOption', [
function (session, args, next) {
}
]).triggerAction({ matches: /choose-time-card[0-9]+-[0-9]+/i});
I tried invoke but this is said to be limited to "internal use" whatever that means. So I tried this but it doesnt work:
bot.on('invoke', function (event) {
var msg = new builder.Message().address(event.address);
msg.data.text = "I see that you clicked a button.";
bot.send(msg);
bot.send(JSON.stringify(event));
});
Does anyone know?
A few comments on this:
The SDK release from a few days ago 3.14 reinstated the Invoke ActionType.
To accomplish what you want to do it is as simple as something like this:
var bot = new builder.UniversalBot(connector, function(session) {
if(session.message.text === "your messageback value"){
//do stuff
}else{
session.send("You said: %s", session.message.text);
}
}).set('storage', inMemoryStorage);

beginner node.js callback example [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm pretty novice in nodejs
This is a very easy php example that I want to write in nodejs
$key='foo';
$inside= openthedoor($key);
if(!$inside){ //wrong key
$key= getanewkey();//get a new key
$inside= openthedoor($key);//open the door again
}
How can I do this callback in nodejs?
appologies for the stupid question.
Keep in mind that you can still write things synchronously in Node.js, but if openthedoor() did happen to require a callback function, this is what it'd look like:
var key = 'foo';
openthedoor(key, function(inside) {
if (!inside) {
key = getanewkey();
openthedoor(key, function(inside) {
// check if we're inside again
});
}
});
A callback function is a function that is called on completion of another function. In the example, you are passing this function:
var callback = function(inside) {
if (!inside) {
// do something else
}
});
Into this function to be called when there is a result:
openthedoor(key, callback);

Express + NodeJS Documentation [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 5 years ago.
Improve this question
Hi Everyone I am newbie to Express + NodeJS. I come from Java and trying to get caught up on Node now so please be gentle if I ask some basic questions (I have spent the last 2 days catching up on this stuff)
My questions are around documentation.
So when I look through some of the examples present on Express site I see the following
app.get('/users/:id?', function(req, res, next){
......
});
and sometimes
app.get('/users/:id?', function(req, res){
......
});
where is the documentation for me to determine how many paramaters go into the function?? first theres was req, res and next but then it had req and res.
Second question: where is the documentation for what is available on the request and response objects along with other method that are available as part of the framework?
I looked up the documenation here http://expressjs.com/guide.html#req.header() but I can't imagine this is entire doc because i notice methods being used on examples that are not present on this documentation.
Can someone point me to the most commonly used docs for express + nodeJS development? If you can list all the links here I would be very grateful!
First question: You need to slow down a minute. Do you have any experience with another language besides Java? Javascript does not have method signatures in the way you know from Java. Here is a quick example:
function foo(bar, baz, qux) {
var result = bar + baz;
if(qux) {
result += qux;
}
return result;
}
foo(1, 2);
// => 3
foo(1, 2, 3);
// => 6
It's a contrived example, but it shows that you can declare a function which takes 3 arguments, and only use two of them. In fact, it could use arguments directly and accept even more arguments than specified in the function declaration!
function bar(foo) {
if(arguments.length > 1) {
var baz = arguments[1];
return foo + baz;
}
return foo;
}
bar(2);
// => 2
bar(2, 4);
// => 6
Anyway, in short, your route handler function(req, res, next) {} will always be called with req, res, and next -- but it just might be the case that you don't need next (because you won't ever pass on control, perhaps), so you omit it (it will still be there, in your arguments object, just not scoped as next). Some feel this is sloppy, others that it's succinct.
Second question: Here is node.js docs, http.ServerRequest, http.ServerResponse. You already know the Express guide.
JavaScript is kind of lax about the number of parameters a function takes. If a function takes two parameters, you can still pass it five arguments β€” the first two you pass will go in the named parameters, and the rest will only be available through the arguments object. (Similarly, if you write a function that takes three arguments, a caller can still pass only two and the third will have the value undefined.)
So basically, the function will always get three arguments, but a lot of times you have no intention of using the next continuation, so you can just leave it off and JavaScript will silently swallow it.
As for documentation, that guide is the official documentation for Express. The docs for Node.js are at nodejs.org. Express's modules are generally based off their vanilla Node equivalents (e.g. the server is based off Node's http.Server).

Resources