I'm trying to get the following Javascript:
http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));
});
Using the following Coffeescript:
http.createServer app
.listen app.get 'port', () ->
console.log 'Express server listening on port'
which results in:
http.createServer(app).listen(app.get('port', function() {
return console.log('Express server listening on port');
The problem being that this obviously puts the callback function as the second parameter to app.get rather than as the second parameter to http.listen.
http
.createServer app
.listen app.get('port'), ->
console.log "Express server listening on port #{app.get 'port'}"
You just needed to include parentheses around the app.get argument.
Note, see http://contribute.jquery.org/style-guide/js/ for jQuery approved styling syntax. Not all rules apply to coffeescript, but the method chaining is very helpful.
Related
i'm facing an issue with my socket client on next.js . i have created a context for providing my socket instance for all components in the application , the problem is that when i want to use the socket context on my component i am using the useeffect hook be called once the socket is changed and i will handle on message call ( like any tutorial i have seen on the web ) but with new message on the socket the useeffect is not called at all . for those who may think this is context issue i should say its not i have tested socket initiation on the component itslef and still useeffect not being called .
here is the way im using the socket instance :
export default function MyComp(props){
const cookies = new Cookies()
const token = cookies.get('token');
const socket = io(routes.socket_url, { path: '/socket',
transports: ['websocket'],
query:{
token,
user_id:'someuserid'
}
});
useEffect(() => {
console.log('socket changed');
console.log(socket);
console.log('socket changed');
},[socket])
}
i can actually see the connection on my devtools and also see the message in the network tab so it means we have a connection (also checked on server ) but the console.log() part is never called on new messages .
and here is my component using the context .
export default function MyComp(props){
const socket = useContext(SocketContext);
useEffect(() => {
console.log('socket changed');
console.log(socket);
console.log('socket changed');
},[socket])
}
the connection in this one is also available in the devtools and it gets the new message on networks tab but the logging is never called in useeffect .
thank you for any help .
guys i found the answer . i was using socket.io-client v 3.1.1 and i started testing other versions . for some strange reason
in version 3 socket instance is not receiving any messages though the connection is already stablished and i can see the messages coming in the networks tab .
anyways i changed version from 3 to 2.1.1 and its working like a charm .
I hit a Protractor issue, if I run this within "ts-node demo.js" it works well and can output the response code and response body.
But if I run this in Protractor it block, then can't get the expected output response code and body, seems like Protractor won't wait for the callback.
In this situation, how can I output the response code and boday?
it(Check manifests V2 api, async() => {
const https = require('https')
const options = {
hostname: 'demo-quayecosystem-quay-quay.com',
port: 443,
path: '/v2/quay/multiarchdemo/manifests/latest',
method: 'GET',
headers: {
'Accept': 'application/vnd.docker.distribution.manifest.list.v2+json'
}
}
https.request(options, res => {
browser.getTitle().then(()=>{
console.log("starting.........");
console.log(`statusCode: ${res.statusCode}`)
res.on('data', d => {
process.stdout.write(d)
})
})
})
})
The function above is an async and when you make your function async, then you should use the await keyword in front of the https.request or return it like this.
return https.request...
And another thing that could lead to problems are...
https.request is making a direct HTTP request, without using a browser
broser.getTitle() is using the browser to interact with the web page.
Be aware - browser uses the browser, and http.request uses direct HTTP from node.js - these are two different things. And it will lead to unpredictable things to mix them. So consider if you want to "test as a user" and then use the browser, or if you want to do the fastest possible test and "test as a website or javascript" and use HTTP.request.
Try reading the async/await page on the Protractor website.
https://www.protractortest.org/#/async-await
If you are puzzled about async/await consider seeing the video from Fun Fun Function on promises https://www.youtube.com/watch?v=568g8hxJJp4&t=251s.
This example from Socket.IO website is confusing me. Sending and getting data (acknowledgements):
Client:
<script>
socket.on('connect', function () {
socket.emit('ferret', 'tobi', function (data) {
console.log(data); // data will be 'woot'
});
});
</script>
Server:
io.sockets.on('connection', function (socket) {
socket.on('ferret', function (name, fn) {
fn('woot');
});
});
I'm actually reproducing this example. What I can't understand is:
Q1: How does this work in the first place. Does the server (when executing fn) automagically emits the result to the client? Does Socket.IO bind fn to the client third parameter of emit?
Q2: What's the (unused) name parameter in server anonymous function (name, fn)? Logging it shows that it's undefined, why?
Found by myself, correct me if I'm wrong:
name (what unlucky name from the official documentation!!!) is actually the data sent by the client.
fn corresponds to the 3th parameter of client code, and when executed (from the server) automagically (?) sends the data back to the client. Amazing!
Indeed; it gets a lot clearer if you rename "fn" to "callback", as seen here: Acknowledgment for socket.io custom event. That callback is never executed on the server side; the server simply sends the data passed to the callback (in this case, the string "woot") back to the client as an acknowledgement. The callback is then executed on the client using the data sent by the server.
To send data from client to server
socket.emit("Idofhtmltag",value);
To receive data from server, on client html add this
socket.io("Idofhtmltag",function(msg){ }) ;
I've got a node.js application that 'streams' tweets to users. At the moment, it just searches Twitter for a hard-coded string, but I'd like to allow users to configure this in the URL (eg. by visiting /?q=stackoverflow).
At the moment, my code looks a bit like this:
app.get('/', function (req, res) {
// page rendering skipped
io.sockets.on('connection', function (socket) {
twit.stream('user', {track: 'stackoverflow'}, function(stream) {
stream.on('data', function (data) {
socket.volatile.emit('tweet', data);
}
});
});
});
The question is, how do I make it so that each user can see a different stream of tweets simultaneously? At the moment, it works fine in a single browser tab, but it falls over as soon as a second one is opened - and the error is fairly deep down inside socket.io. Am I misusing it?
I haven't fully got my head around socket.io yet, so that could be the issue.
Thanks in advance!
Every time a new request comes in, you are redefining the connection callback with io.sockets.on - you should move that block of code outside of app.get, after your initialization statement of the io object.
I'm working on my first node.js / express / mongoose app and I'm facing a problem due to asynchronisation mechanism of node.js. It seems I do not do the thing correctly...
Here is the test route I defined using express:
app.get('/test', function(req, res){
var mod = mongoose.model('MyModel');
mod.find({},function(err, records){
records.forEach(function(record){
console.log('Record found:' + record.id);
// res.send('Thing retrieved:' + record.id);
});
});
});
When I issue a http://localhost/test, I'd like to get the list of records of type 'MyModel' in the response.
The code above is working fine but when it comes to returning this whole list to the client... it does not work (the commented res.send line) and only returned the first record.
I'm very new to node.js so I do not know if it's the good solution to embed several callback functions within the first callback function of app.get . How could I have the whole list returned ?
Any idea ?
What you should be doing is:
mod.find({},function(err, records){
res.writeHead(200, {'Content-Length': body.length});
records.forEach(function(record){
res.write('Thing retrieved:' + record.id);
});
});
Please always check the documentation as well:
http://nodejs.org/docs/v0.3.8/api/http.html#response.write
I missed that you was using express, the send function is part of express and extend's the serverResponse object of node (my bad).
but my answer still applies, express's send function sends the data using ServerResponse.end() so there for the socket get's closed and you cannot send data any more, using the write function uses the native function.
You may also want to call res.end() when the request is fully completed as some item's within express may be affected