I have a file on main root as
test_file.js
Following is the code inside it
var config = require('config');
var Ctrl = require('./Controllers');
var port = process.env.PORT || config.get("PORT") || 3000;
var cors = require('cors');
var express = require('express');
var app = express();
var router = express.Router();
app.use(cors());
app.use(router);
var server = require('http').createServer(app);
var io = require('socket.io')(server, {'pingInterval': 4000, 'pingTimeout': 6000});
io.on('connection', Ctrl.connection);
console.log("Opening at port " + port);
server.listen(port, function () {
});
module.exports = router;
require('./Routes')();
I have another file in path
/Controllers/index.js
i want to pass out io to index.js too, here is its code
var Promise = require('q').Promise;
var config = require('config');
var mysql = require('mysql');
/// I want to get var io = require('../test_file.js');
/**Initialization socket connection */
exports.connection = function (socket) {
if (!(socket.handshake.query.accountType != null && socket.handshake.query.id != null && socket.handshake.query.accessKey != null
&& socket.handshake.query.id > 0)) {
socket.disconnect();
return;
}
Now i am confused about module.exports and exports, my module.exports is already passing out to another file, i want to add another variable i-e io and pass it to controllers file. How can i do that
In respond to the query,
app.use(router);
var server = require('http').createServer(app);
var io = require('socket.io')(server, {'pingInterval': 4000, 'pingTimeout': 6000});
module.exports = {
router: router,
io: io
};
io.on('connection', Ctrl.connection);
console.log("Opening at port " + port);
server.listen(port, function () {
});
require('./Routes')();
In Controllers/index.js
var Promise = require('q').Promise;
var config = require('config');
var mysql = require('mysql');
var Driver = require('./driver');
var User = require('./user');
var io = require('../test_file.js').io;
console.log("logging");
console.log(io);
the result is {} for io
exports is just module.exports's little helper. Your module returns module.exports to the caller ultimately, not exports. All exports does is collect properties and attach them to module.exports IF module.exports doesn't have something on it already. If there's something attached to module.exports already, everything on exports is ignored.
you can pass both as the object
module.exports = {
router: router,
io: io
};
Please refer this doc for more explanation
Edit
Access object via module.exports
file.js
var express = require('express');
var router = express.Router();
/* GET users listing. */
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
module.exports = {router:router};
Acess it with
var router=require('./file').router
OR
var router=require('./file');
router.router
Related
I am just starting in nodejs.
I am instantiating a logger (Pino) in server.js which is the entry point. I only want to create one instance of that logger and use it in other modules.
'use strict';
const express = require('express');
const pino = require('pino');
const log = pino({ level: process.env.LOG_LEVEL || 'info' });
const ping = require('./routes/ping'); //new
const app = express();
app.use('/api/ping', ping);
const port = 3000;
app.listen(port, () => {
console.log(`API server started on ${port}... ^C to end`);
});
module.exports = { app, log }; //edited
So in ping.js how do I get access to log in services.js?
const express = require('express');
const router = express.Router();
const { log } = require('../server'); //edited
router.get('/', async function(req, res) {
log.info('someone pinged');
res.sendStatus(200);
});
module.exports = router;
Edited with suggestions.
You can attach the logger as a property on your app object or on app.locals. Then a reference to it will be accessible through req.app.logger or req.app.locals.logger or whatever in your middlewares and route handlers.
'use strict';
const path = require('path');
const express = require('express');
const ping = require('./routes/ping');
const pino = require('pino');
const log = pino({ level: process.env.LOG_LEVEL || 'info' });
var app = module.exports = express();
app
.use('/api/ping', ping);
const port = config.SERVER_PORT || 3000;
app.listen(port, () => {
console.log(`API server started on ${port}... ^C to end`);
});
module.exports = {app,pino}
Now you can import the same pino instance anywhere.
const log = require('./server.js').pino
I am getting the following error:
olddognewtrix123:~/workspace (master) $ node server.js
/home/ubuntu/workspace/app/routes/index.js:7
app.route('/')
^
TypeError: app.route is not a function
...and have no idea why.
I am building this in c9.io
Here is the updated github repo:
https://github.com/olddognewtrix123/nodeJSvignettes
Here is the code wherein I believe the error lies:
server,js:
var express = require('express');
var session = require('express-session');
var path = require('path');
var mongoose = require('mongoose');
var port = process.env.PORT || 8080;
var mongodb=require("mongodb")
var MongoClient = mongodb.MongoClient;
var routes = require('./app/routes/index.js');
var app = express();
app.use('/controllers', express.static(process.cwd() + '/app/controllers'));
app.use('/public', express.static(process.cwd() + '/public'));
var port = process.env.PORT || 8080;
routes(app);
app.listen(port, function () {
console.log('Node.js listening on port ' + port + '...');
});
index.js:
'use strict';
var path = process.cwd();
module.exports = function (app){
app.route('/')
.get(function (req, res) {
res.sendFile(path + '/public/index.html');
});
};
Why am I getting this error????
Any help is appreciated!
There are two syntax you can try .
There is no app.route as you are passing.
index.js:
'use strict';
var path = process.cwd();
module.exports = function (app){
app.get('/',function (req, res) {
res.sendFile(path + '/public/index.html');
});
};
OR THIS
'use strict';
var path = process.cwd();
var router = express.Router()
module.exports = function (app){
router.get('/', function (req, res) {
res.sendFile(path + '/public/index.html');
})
};
How can i read cookie on node js ??
var socket = require( 'socket.io' );
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = socket.listen( server );
var port = process.env.PORT || 8000;
var mysql = require('mysql');
function parseCookies (request) {
var list = {},
rc = request.headers.cookie;
rc && rc.split(';').forEach(function( cookie ) {
var parts = cookie.split('=');
list[parts.shift().trim()] = decodeURI(parts.join('='));
});
return list;
}
http.createServer(function (request, response) {
// To Read a Cookie
var user_id= cookies.realtimeid;
console.log(user_id);
});
server.listen(port, function () {
console.log('Server listening at port %d', port);
var cookies = parseCookies();
console.log(cookies);
});
I am new on node and socket. I have to read cookie value that is set by codeignter.
How can i send header request on parseCookies from server.listen.
I see you are using express, so I suggest you to use the very well known module for it. cookie-parser https://www.npmjs.com/package/cookie-parser
Installation
npm install cookie-parser
HOW TO USE IT
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
So basically after your mysql require you can do app.use(cookieParser())
And then in every request you do in the req variable you will find the cookies with req.cookies
Example
var express = require('express')
var cookieParser = require('cookie-parser')
var app = express()
app.use(cookieParser())
app.get('/', function(req, res) {
console.log("Cookies: ", req.cookies)
})
app.listen(8080)
I am trying to retrieve the port number on which NodeJS is listening on. Currently I saving the port number value in app.js variable and trying to access it in index.js file. However, I am getting undefined value in index.js file. I am not sure why is this happening. How can I fix this?
index.js
var express = require('express');
var app = require('../app');
var router = express.Router();
var socket = require('socket.io');
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
console.log("port: "+ app.portNumber);
socket.listen(app.portNumber);
});
module.exports = router;
app.js:
var portNumber;
// rest of the controller code which calls the correct routes when a webpage is requested.
www.js:
/**
* Get port from environment and store in Express.
*/
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
app.portNumber = port;
This will export the variable port and will be available whenever you
import it var app = require('../app');
app.js:
var port = normalizePort(process.env.PORT || '3000');
app.set('port', port);
app.portNumber = port;
exports = module.exports = {
portNumber : port
}
index.js:
var app = require('../app');
console.log("port: "+ app.portNumber);
I'm trying to use simplewebrtc in my app, I already have a simple nodejs server with express web framework. But to use simpleWebrtc we have to install signal master. I'm looking at the source code for the server.js file in the signal master package but I can't figure out how to combine this server.js with my already existing app.js file. This is basically my app.js
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var mongoose = require('mongoose');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
console.log("connected to index");
});
and this is server.js of signalMaster
/*global console*/
var yetify = require('yetify'),
config = require('getconfig'),
uuid = require('node-uuid'),
crypto = require('crypto'),
fs = require('fs'),
port = parseInt(process.env.PORT || config.server.port, 10),
server_handler = function (req, res) {
res.writeHead(404);
res.end();
},
server = null;
// Create an http(s) server instance to that socket.io can listen to
if (config.server.secure) {
server = require('https').Server({
key: fs.readFileSync(config.server.key),
cert: fs.readFileSync(config.server.cert),
passphrase: config.server.password
}, server_handler);
} else {
server = require('http').Server(server_handler);
}
server.listen(port);
var io = require('socket.io').listen(server);
if (config.logLevel) {
// https://github.com/Automattic/socket.io/wiki/Configuring-Socket.IO
io.set('log level', config.logLevel);
}
etc, etc you can look at the rest by downloading the zip. I thought it would be just replacing server with http, but the server=null doesn't really make sense. All the dependencies are in the directory of the signalMaster unzipped file. I was reading about signalMaster here.
You will need something like this
var os = require('os');
var static = require('node-static');
var http = require('http');
var socketIO = require('socket.io');
var fileServer = new(static.Server)();
var app = http.createServer(function (req, res) {
fileServer.serve(req, res);
}).listen(2013);
var io = socketIO.listen(app);
io.sockets.on('connection', function (socket){
...
socket.on('join', function (message) {
...
}
...
}
i hope this help u