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)
Related
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, () => {
//...
});
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;
So I 100% copy pasted a code from the link below and I get the error below. I have installed all the dependencies required. I have used socket.io previously without problems, but never socket.io.users. The goal is to identify each PC as user.
var chatUsers = socketUsers.Users.of('/chat'); //
^
TypeError: Object #<Users> has no method 'of'
at Object.<anonymous> (/var/www/100moneta/components_not_larval/socket-user.js:16:35)
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:902:3
My code:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var socketUsers = require('socket.io.users');
socketUsers.Session(app);//IMPORTANT
var rootIo = require('socket.io')(server); //default '/' as namespace.
var chatIo = rootIo.of('/chat');
var rootUsers = socketUsers.Users; /* default '/' as namespace. Each namespace has IT's OWN users object list,
but the Id of a user of any other namespace may has the same value if request comes from the same client-machine-user.
This makes easy to keep a kind of synchronization between all users of all different namespaces. */
var chatUsers = socketUsers.Users.of('/chat'); //
rootIo.use(socketUsers.Middleware());//IMPORTANT but no errors if you want to skip it for a io.of(namespace) that you don't want the socket.io.users' support.
chatUsers.use(socketUsers.Middleware());
chatUsers.on('connected',function(user){
console.log(user.id + ' has connected to the CHAT');
user.set('username', 'username setted by server side'); /*at the store property you can store any type of properties
and objects you want to share between your user's sockets. */
user.socket.on('any event', function(data){ //user.socket is the current socket, to get all connected sockets from this user, use: user.sockets
});
chatIo.emit('set username',user.get('username')); //or user.store.username
});
rootUsers.on('connected',function(user){
console.log('User has connected with ID: '+ user.id);
});
rootUsers.on('connection',function(user){
console.log('Socket ID: '+user.socket.id+' is user with ID: '+user.id);
});
rootUsers.on('disconnected',function(user){
console.log('User with ID: '+user.id+'is gone away :(');
});
//You can still use the io.on events, but the execution is after connected and connection of the 'users' and 'chatUsers', no matter the order.
rootIo.on('connection',function(socket){
console.log('IO DEBUG: Socket '+ socket.id+ ' is ready \n');
});
Link with the code and tutorial: https://www.npmjs.com/package/socket.io.users
I create a node app that is working locally. I need help to modify server.js below so that it can work on heroku.
server.js:
var http = require('http');
var session = require('cookie-session');
var port = 9500;
var Assets = require('./backend/Assets');
var API = require('./backend/API');
var Default = require('./backend/Default');
var Chat = require('./backend/Chat');
var Router = require('./frontend/js/lib/router')();
Router
.add('static', Assets)
.add('node_modules', Assets)
.add('tests', Assets)
.add('api', API)
.add(Default);
var checkSession = function(req, res) {
session({
keys: ['nodejs-by-example']
})(req, res, function() {
process(req, res);
});
}
var process = function(req, res) {
Router.check(req.url, [req, res]);
}
var app = http.createServer(checkSession).listen(port, '127.0.0.1');
console.log("Listening on 127.0.0.1:" + port);
Chat(app);
I tried:
var port = Number(process.env.PORT || 9000);
But it didn't work. I got this error:
users-MacBook-Pro-6:project user$ node server
/Users/user/Desktop/project/server.js:3
var port = Number(process.env.PORT || 5000);
TypeError: Cannot read property 'env' of undefined
at Object.<anonymous> (/Users/user/Desktop/project/server.js:3:26)
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:906:3
It looks like you are getting an undefined process variable. To troubleshoot you should do a console.dir(process) which will print out everything on the process variable including your environment variables.
As well you can try doing this - heroku config:set NODE_ENV=production per heroku support
Could possibly be related to this.
Update
To further troubleshoot you will need to install a logging addon-
heroku addons:create papertrail
After you install you will be able to navigate to the add-on and see any messages that are being logged related to the deployment as well as your console.dir and console.log printouts.
I have created a nodejs http server
var http = require("http");
var url = require("url");
var express = require('express');
var app = express();
function start(route, handle){
function onRequest(request,response){
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
route(handle, pathname, response, request);
}
http.createServer(onRequest).listen(8888);
console.log("Server has started");
app.listen(8888);
console.log('Express app listening on port 8888');
}
it gives error
f:\Labs\nodejs\webapp>node index.js
Server has started
Express app listening on port 8888
events.js:66
throw arguments[1]; // Unhandled 'error' event
^
Error: listen EADDRINUSE
at errnoException (net.js:769:11)
at Server._listen2 (net.js:909:14)
at listen (net.js:936:10)
at Server.listen (net.js:985:5)
at Function.app.listen (f:\Labs\nodejs\webapp\node_modules\express\lib\appli
cation.js:532:24)
at Object.start (f:\Labs\nodejs\webapp\server.js:15:6)
at Object.<anonymous> (f:\Labs\nodejs\webapp\index.js:11:8)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:356:32)
when i change the port of app.listen it dont throw this error, what can be done?
will changing port other than server port will keep the session of the server on another port??
and how can i access this app variable in other js page to get/set the data?
If you intend to run on the same port, you can see if you have currently running node processes with
ps aux | grep node
and then kill -9 PROCESSID
You can't have multiple things listening on the same port like this, hence the EADDRINUSE error. If you want to create your own http server while using Express, you can do it like this:
var express = require('express');
var https = require('https');
var http = require('http');
var app = express();
http.createServer(app).listen(8888);
https.createServer(options, app).listen(443);
From the Express docs:
The app returned by express() is in fact a JavaScript Function,
designed to be passed to node's http servers as a callback to handle
requests.
Or you can just do
app.listen(8888);
And then Express will setup an http server for you.
You would then set up your routes in Express to actually handle requests coming in. With Express, routes look like this:
app.get('/foo/:fooId', function(req, res, next) {
// get foo and then render a template
res.render('foo.html', foo);
});
If you want to access your app in other modules (usually for testing) you can just export it like any other variable:
module.exports.app = app;
You'll then be able to require('./app').app in other modules.