node.js: importing socket.io with es6 [duplicate] - node.js

This question already has answers here:
Pass options to ES6 module imports
(9 answers)
Closed 4 years ago.
I am writing a sample code to handle socket connections in node.js using es6 script, on importing socket.io it raises an error
import {
PORT
} from './config';
import express from 'express';
import io from 'socket.io';
var app = express();
// respond with "hello world" when a GET request is made to the homepage
app.get('/', function(req, res) {
res.send('hello world')
});
io.on('connection', function(socket) {
console.log('a user connected');
});
app.listen(PORT, () => console.log(`Example app listening on port ${PORT}!`));
The error is
/index.js:17
_socket.default.on('connection', function (socket) {
^
TypeError: _socket.default.on is not a function
at Object.on (/Users/digvijay.upadhyay/digvijayu/websocket_with_node/src/index.js:15:4)
at Module._compile (module.js:643:30)
at Module._compile (/Users/digvijay.upadhyay/digvijayu/websocket_with_node/node_modules/pirates/lib/index.js:83:24)
at Module._extensions..js (module.js:654:10)
at Object.newLoader [as .js] (/Users/digvijay.upadhyay/digvijayu/websocket_with_node/node_modules/pirates/lib/index.js:88:7)
at Module.load (module.js:556:32)
at tryModuleLoad (module.js:499:12)
at Function.Module._load (module.js:491:3)
at Function.Module.runMain (module.js:684:10)
at Object. (/Users/digvijay.upadhyay/digvijayu/websocket_with_node/node_modules/#babel/node/lib/_babel-node.js:224:23)
[nodemon] app crashed - waiting for file changes before starting...
Successfully compiled 2 files with Babel. Successfully compiled 2
files with Babel.

You need to invoke function require('socket.io')() and pass there an express instance.
Please look at added code example:
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const app = express();
const server = http.createServer(app);
// this line \/
const io = socketIO(server);
// this line /\
io.on('connection', (socket) => {
//...
});
server.listen(port, () => {
//...
});

Related

Run express api server and socket alongside nest js?

I have an existing API project in express js. Socket js is also implemented here. I want to Implement a new module in nest js and run express, socket, and nest on the same server, where express and socket-based APIs will remain unchanged. I could successfully run express and nest on the same server but the socket is not working.
Bellow app.js creates an express server and exports the server.
App.js
const express = require("express");
const app = express();
app.get("/hello", (req, res) => {
res.json({
success: true
})
});
module.exports = {
expressApp: app
};
In the entry point of the nest project, the expressApp will be Imported and will be adapted with nest by ExpressAdapter function
main.ts
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
import { expressApp } from "../../app.js";
import { ExpressAdapter } from '#nestjs/platform-express';
async function bootstrap() {
const app = await NestFactory.create(AppModule, new ExpressAdapter(expressApp));
return await app.listen(3000);
}
bootstrap();
This works fine. The express route and the nest controller return success.
If I initiate the socket to App.js
const io = require('socket.io')(app);
io.on('connection', () => { console.log("connected") });
then it returns an error as the app is not an http.Server instance.
Error: You are trying to attach socket.io to an express request handler function. Please pass a http.Server instance.
at Server.attach (C:\Users\yotech20\Desktop\combine\node_modules\socket.io\dist\index.js:167:19)
at new Server (C:\Users\yotech20\Desktop\combine\node_modules\socket.io\dist\index.js:75:18)
at module.exports (C:\Users\yotech20\Desktop\combine\node_modules\socket.io\dist\index.js:599:33)
at Object.<anonymous> (C:\Users\yotech20\Desktop\combine\app.js:31:30)
at Module._compile (internal/modules/cjs/loader.js:1085:14)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1114:10)
at Module.load (internal/modules/cjs/loader.js:950:32)
at Function.Module._load (internal/modules/cjs/loader.js:790:12)
at Module.require (internal/modules/cjs/loader.js:974:19)
at require (internal/modules/cjs/helpers.js:101:18)
I cannot create a server instance in App.js
const server = require('http').createServer(app);
const io = require('socket.io')(server);
io.on('connection', () => { console.log("connected") });
and pass that instance in the socket as the nest doesn't allow it.
Now, How Can I run this socket server with express and nest?

SyntaxError: Unexpected token const

I am creating a web server that will allow users make a request for fortunes, and get the data which I specified in my fortunes.json file. I am using express in node to do this.
I start my server this way npm run dev, however when I do so, I get the following error:
SyntaxError: Unexpected token const
at Module._compile (internal/modules/cjs/loader.js:720:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:643:32)
at Function.Module._load (internal/modules/cjs/loader.js:556:12)
at Function.Module.runMain (internal/modules/cjs/loader.js:839:10)
at internal/main/run_main_module.js:17:11
Does anybody have an idea what I am doing wrong, my syntax, and packages.json file, etc. all seems to be fine but I am still getting this.
I am expecting to see "server listening on port 3000" when I run the server however I get a token error.
const express = require('express');
const port = 3000,
const app = express();
app.get('/fortunes', (req,res) => {
console.log('requesting fortunes');
});
app.listen(port, () => console.log('Listening on port ${port}'));
You have two issues in your code.
1 . when you are initializing variable:
As you have put ',' (comma) thus you cannot specify its declaration again.
your code
const port = 3000,
const app = express();
Do like this :
const port = 3000,
app = express();
or use this :
const port = 3000;
const app = express();
When using string template use `(backtick).
app.listen(port, () => console.log(`Listening on port ${port}`));
Try below Code:
const express = require('express');
const port = 3000,
app = express();
app.get('/fortunes', (req,res) => {
console.log('requesting fortunes');
});
app.listen(port, () => console.log(`Listening on port ${port}`));
In ECMAScript 2015, you can use backtic as follow in your code:
app.listen(port, () => console.log(`Listening on port ${port}`));
or use :
app.listen(3000, () => console.log('Connected to the port'));

Loading the same native module into TWO node.js threads

I have a native C++ module that is spun up by a worker thread from node.js, which works great. From within that node module, I can call my native methods like "AddToLog()" and it works great.
I also need to service web requests, which is my dilemma. So I used express and included a file to start it up on a worker thread. That also works fine - both my native code and the express web server are working at the same time.
However, when I try to 'require' my native module in the file that starts the web server, I get an error that the native module could not be registered.
Have I hit a fundamental limitation where node.js cannot load the same native module on two different worker threads? Or this is as simple as a syntax issue?
My hunch is that I can fix this by making the module context aware, but I'm too new to this to know for sure!
I need the express thread to be able to access the module in order to draw its content. So one thread is running a lighting server that collects data and the other services web requests that describe the current state... if it worked!
// SCRIPT 1
'use strict'
const nightdriver = require('./build/Release/nightdriver.node')
const { Worker } = require('worker_threads');
function startserver()
{
nightdriver.addtolog("[index.js] Starting NightDriver Server");
//nightdriver.startserver();
}
const worker = new Worker("./startweb.js");
nightdriver.addtolog("[index.js] Starting Web Server...");
startserver();
// SCRIPT 2
'use strict'
const nightdriver = require('./build/Release/nightdriver.node')
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World');
})
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
events.js:167
throw er; // Unhandled 'error' event
^
Error: Module did not self-register.
at Object.Module._extensions..node (internal/modules/cjs/loader.js:736:18)
at Module.load (internal/modules/cjs/loader.js:605:32)
at tryModuleLoad (internal/modules/cjs/loader.js:544:12)
at Function.Module._load (internal/modules/cjs/loader.js:536:3)
at Module.require (internal/modules/cjs/loader.js:643:17)
at require (internal/modules/cjs/helpers.js:22:18)
at Object.<anonymous> (/Users/dave/OneDrive/Source/Node/nightdriver/startweb.js:2:21)
at Module._compile (internal/modules/cjs/loader.js:707:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:718:10)
at Module.load (internal/modules/cjs/loader.js:605:32)
Emitted 'error' event at:
at Worker.[kOnErrorMessage] (internal/worker.js:332:10)
at Worker.[kOnMessage] (internal/worker.js:342:37)
at MessagePort.Worker.(anonymous function).on (internal/worker.js:279:57)
at MessagePort.emit (events.js:182:13)
at MessagePort.onmessage (internal/worker.js:84:8)

bin/www app.listen is not a function

I'm trying to run my server from www file but when trying to run it gives me following output. Why I'm getting this error?
I'm using Express 4.16. Is there some problem with node env path? Or it's some other issue?
❯ ./bin/www ✔ master
/Users/me/Test/ExpressAPP/bin/www:6
app.listen(3000, function () {
^
TypeError: app.listen is not a function
at Object.<anonymous> (/Users/me/Test/ExpressAPP/bin/www:6:5)
at Module._compile (module.js:624:30)
at Object.Module._extensions..js (module.js:635:10)
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
at Function.Module._load (module.js:500:3)
at Function.Module.runMain (module.js:665:10)
at startup (bootstrap_node.js:187:16)
at bootstrap_node.js:607:3
./bin/www
#!/usr/bin/env node
var app = require('./../app')
app.listen(3000, function(){
console.log('Listening on port 300')
})
app.js
var express = require('express')
var app = express()
app.get('/', function(request, response){
response.send('OK')
})
module.exports = app
I bet there is no problem with your code. I created a demo with your code snippet. I works as expected. So the issue maybe related to your environment. Can you try delete the node_modules folder and try to reinstall npm packages with npm i -S express command?
And I have two idea help you to resolve your issue.
Add cosole.log(app) in www file and see what the app that you've required is. Is it the same object as you created in app.js?
Double-check your source code is same as what you pasted, especially the module.exports = app. I've lost the s before.
try this code :
/* config/express.js */
var express = require('express');
module.exports = function() {
var app = express();
app.set('port', 3000);
return app;
};
/* server.js */
var http = require('http');
var app = require('./config/express')(); // Notice the additional () here
http.createServer(app).listen(app.get('port'), function() {
console.log("Express Server Runing on port"+ app.get('port'));
});
I had the same issue,
wrong: module.export=app;
right: module.exports=app;

GET http://localhost:3000/socket.io/socket.io.js 404 (Not Found)

I'm trying to stream data to the browser. I'm struggling, however, to connect it to the browser. Here's my html:
<ul class="tweets"></ul>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
jQuery(function ($) {
var tweetList = $('ul.tweets');
socket.on('tweet', function (data) {
tweetList .prepend('<li>' + data.user + ': ' + data.text + '</li>');
});
});
</script>
And here's the relevant parts of my app.js:
var express = require('express')
, twitter = require('ntwitter')
, http = require('http')
, path = require('path');
var app = express();
var io = require('socket.io').listen(app);
app.get('/', function (req, res) { res.sendfile(__dirname + '/index.html'); });
app.listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
io.sockets.volatile.emit('tweets', {
user: data.user.screen_name,
text: data.text,
geo : geo,
latitude: latitude,
longitude: longitude
});
I installed socket.io 0.9.16 via my packages.json file:
"dependencies": {
"express": "3.2.6",
"jade": "*",
"ntwitter":"0.2.10",
"socket.io":"0.9.x"
}
Can anyone help me out here? Why can't it find the file?
Digging a bit deeper. To test the socket, I put this in the app.js:
var socket = io.listen(app);
And I get the error:
TypeError: Object #<Manager> has no method 'listen'
at Object.<anonymous> (/home/andy/dev/node/mytwittermap/app.js:49:17)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:901:3
Your setup needs to look something like this:
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
...
server.listen(app.get('port')); // not 'app.listen'!
Can you try this:
var http = require('http');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
I guess, you will have to instantiate the socket.io server.
You need to instantiate the socket.io connection and
You need to use server.listen() and not app.listen()
Try something like this:
// at the top of app.js
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
// your code
// at the bottom of app.js
server.listen('3000', () => {
console.log('Server listening on Port 3000');
})

Resources