My company have a custom developed logger package, and we want to use that as default logger in fastify. I tried to understand how to register my logger with this simple example below, but fastify always use Pino.
index.js
const log = require("./Logger");
const fastify = require("fastify")({ logger: log });
fastify.get("/", (request, reply) => {
request.log(
"includes request information, but is the same logger instance as `log`"
);
reply.send({ hello: "world" });
});
fastify.listen(3000)
logger.js
function Logger(...args) {
this.args = args;
}
Logger.prototype.info = function(msg) {
console.log("myLogger", msg);
};
logger.js also contains error, debug, fatal, warn, trace, child functions but the functions body is same.
The result is:
{"level":30,"time":1553095994942,"msg":"Server listening at http://127.0.0.1:3000","pid":14543,"hostname":"VirtualBox","v":1}
whitch is the default Pino output.
as explained here, your logger
must have the following methods
So this example works:
function Logger(...args) {
this.args = args;
}
Logger.prototype.info = function (msg) { console.log("myLogger", msg); };
Logger.prototype.error = function (msg) { console.log("myLogger", msg); };
Logger.prototype.debug = function (msg) { console.log("myLogger", msg); };
Logger.prototype.fatal = function (msg) { console.log("myLogger", msg); };
Logger.prototype.warn = function (msg) { console.log("myLogger", msg); };
Logger.prototype.trace = function (msg) { console.log("myLogger", msg); };
Logger.prototype.child = function () { return new Logger() };
const myLogger = new Logger()
const app = require('fastify')({
logger: myLogger
})
app.get("/", (request, reply) => {
request.log.info('hi');
reply.send({ hello: "world" });
});
app.listen(3000)
Here you can check the logger validation applied to your parameter
in case you need log4js,
this is a customized logger that supports json event.
you c
import log4js from "log4js";
import {log4jsConfig} from "./log4js.config.js";
log4js.addLayout('json', function (config) {
return function (logEvent) {
logEvent.application = 'my-app';
logEvent.processId = process.pid;
if (process.env.IP) {
logEvent.ip = process.env.IP;
}
if (process.env.ENV) {
logEvent.ENV = process.env.ENV;
}
if (logEvent.data && logEvent.data.length > 0) {
logEvent.message = logEvent.data[0];
delete logEvent.data;
}
return JSON.stringify(logEvent);
};
});
const log = log4js.getLogger('engine');
log4js.configure(log4jsConfig);
export class AndromedaLogger {
logger;
loggerOptions;
constructor(args) {
this.logger = log;
}
get Logger() {
return this.logger;
}
static configGlobal(options) {
this.loggerOptions = options;
}
info(message) {
this.logger.info(message);
}
error(message, trace) {
this.logger.error(`${message} -> (${trace || 'trace not provided !'})`);
}
warn(message) {
this.logger.warn(message);
}
debug(message, context) {
this.logger.debug(message);
}
trace(message, context) {
this.logger.trace(message);
}
fatal(message, context) {
this.logger.fatal(message);
}
child() {
return new AndromedaLogger()
};
}
log4js config:
const _log4jsConfig = {
appenders: {},
categories: {
default: {
appenders: [],
level: 'trace',
},
},
};
_log4jsConfig.appenders.stdout = {
type: 'stdout',
layout: { type: 'colored' },
};
_log4jsConfig.appenders['file'] = {
type: 'file',
filename: 'logs/app.log',
maxLogSize: 104857600,
numBackups: 3,
};
_log4jsConfig.categories.default.appenders.push('stdout');
_log4jsConfig.categories.default.appenders.push('file');
export const log4jsConfig = _log4jsConfig;
Related
I trying to create a common database connection class using typescript for my nodejs express application that returns the MongoDB database object as follows but I always get TypeError: dbConn.GetInstance is not a function
const config = require("config");
const MongoClient = require('mongodb').MongoClient;
export class dbConn {
private db = null;
static url = config.database.uri;
static options = {
bufferMaxEntries: 0,
reconnectTries: 5000,
useNewUrlParser: true,
useUnifiedTopology: true,
};
private constructor() { }
private static instance: dbConn;
public static GetInstance() {//I also tried removing static keyword but still the error remains
if (dbConn.instance == null)
{
dbConn.instance = new dbConn();
}
return dbConn.instance;
}
public getDb() {
if (dbConn.instance.db) {
return dbConn.instance.db;
}
MongoClient.connect(dbConn.url, dbConn.options, function(err: any, db: any){
if(err) {
console.log(err);
return null;
}
dbConn.instance.db = db.db(config.database.name);
return dbConn.instance.db;
});
}
}
Updated 01-Aug-2020
I invoke the above instance from app.ts and my controllers as follows:
app.ts file
const dbConn = require('./utils/db/dbConn');
...//code removed for clarity
const app = express();
const server = http.createServer(app);
...//code removed for clarity
server.listen(port, ()=> {
dbConn.GetInstance().getDb();//I get the error here
console.log('Server running')
});
module.exports = app;
my controller file
getAll = async (pageNumber:any, pageSize:any) : Promise<PageResult<Team>> => {
return new Promise<PageResult<Team>>(async function (resolve, reject){
let result = new PageResult<Team>(pageSize, pageNumber);
var dbo = dbConn.GetInstance().getDb();//same error here too.
var query = {};
var recCount = await dbo.collection("teams").find().count();
if (recCount == 0) {
result.IsSuccessful = true;
result.ReasonForFailure = process.env.NO_RECORDS || "No record(s) to show.";
return resolve(result);
}
if (pageSize == -1) { //-1 means to return all records
dbo.collection("teams")
.find(query)
.sort({ name: 1 })
.toArray(function(err: any, resultSet: any) {
if (err) {
result.IsSuccessful = false;
result.ReasonForFailure = err.message;
return reject(result);
} else {
result.IsSuccessful = true;
result.TotalRecords = recCount;
result.PageNumber = parseInt(pageNumber);
result.PageSize = parseInt(pageSize);
result.Data = resultSet;
return resolve(result);
}
});
} else {
dbo.collection("teams")
.find(query)
.sort({ name: 1 })
.skip((parseInt(pageNumber)-1)*parseInt(pageSize))
.limit(parseInt(pageSize)).toArray(function(err: any, resultSet: any) {
if (err) {
result.IsSuccessful = false;
result.ReasonForFailure = err.message;
return reject(result);
} else {
result.IsSuccessful = true;
result.TotalRecords = recCount;
result.PageNumber = parseInt(pageNumber);
result.PageSize = parseInt(pageSize);
result.Data = resultSet;
return resolve(result);
}
});
}
});
}
Can you please assist what is wrong or what is the missing piece to get this to work?
Thanks,
Hemant.
It seems you're using commonjs as module-resolution strategy. Your import will be the problem in that case. Try changing it to:
const dbConn = require('./utils/db/dbConn').dbConn;
or
const { dbConn } = require('./utils/db/dbConn');
or
import {dbConn } from './utils/db/dbConn';
Here's a simple example to show what's going on. Consider this simple ts-class:
export class TestClass {
static test():void {
console.log("it works")
}
}
It will be transpiled into:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.TestClass = void 0;
class TestClass {
static test() {
console.log("in workds");
}
}
exports.TestClass = TestClass;
//# sourceMappingURL=index.js.map
If you then require this with const TestClassModule = require('./test-class');, TestClassModule will yield:
{ TestClass: [Function: TestClass] }
Hence, you need to use const { TestClass } = require('./test-class');.
I have a mailListenerWrapper.js where I define my imap class:
mailListenerWrapper.js:
const simpleParser = require("mailparser").simpleParser;
const Imap = require("imap");
const striptags = require("striptags");
const BlackListModel = require("./models/blacklist");
const RecEmailConfigModel = require("./models/emailConfig");
const ReceivedEmailModel = require("./models/receivedMail");
const Base64 = require("js-base64").Base64;
const _ = require("lodash");
const logger = require("./helpers/logger");
require("dotenv").config();
class MailListenerWrapper {
constructor() {
this.imap = null;
this.init();
}
async init() {
try {
const getRecEmailConfig = await RecEmailConfigModel.findOne({});
if (getRecEmailConfig) {
getRecEmailConfig.password = Base64.decode(getRecEmailConfig.password);
this.imap = new Imap({
user: getRecEmailConfig.user,
password: getRecEmailConfig.password,
host: getRecEmailConfig.host,
port: getRecEmailConfig.port,
tls: getRecEmailConfig.tls,
tlsOptions: {
rejectUnauthorized: false,
authTimeout: 10000
}
});
} else {
return false;
}
let lastMessage = 0;
const openInbox = cb => {
this.imap.openBox("INBOX", true, cb);
};
const regEmail = /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/g;
this.imap.once("ready", () => {
openInbox((err, box) => {
if (err) {
logger.log({ level: "error", message: err });
return false;
}
lastMessage = box.messages.total;
this.imap.on("mail", numberOfNewMessages => {
const newEmail = {};
// const numberOfNewMessages = 0
lastMessage = lastMessage + numberOfNewMessages;
const f = this.imap.seq.fetch(lastMessage + ":" + lastMessage, {
bodies: ["HEADER.FIELDS (SUBJECT FROM)", ""],
struct: true
});
f.on("message", msg => {
msg.on("body", async stream => {
try {
const parsed = await simpleParser(stream);
if (parsed.headers.get("subject")) {
// ################ HEADER ################ \\
newEmail.title = parsed.headers.get("subject");
const getFrom = parsed.headers.get("from").text.split(" <");
// ############################ //
console.log(getFrom); // executes twice here already
// ########################### //
if (getFrom.length === 2) {
newEmail.name = getFrom[0];
newEmail.email = getFrom[1].match(regEmail).join("\n");
}
// ################ HEADER ################ \\
}
if (parsed.text) {
// ################ TEXT ################ \\
newEmail.text = striptags(parsed.text).toString("utf8");
// ################ TEXT ################ \\
}
if (
newEmail.name &&
newEmail.email &&
newEmail.title &&
newEmail.text
) {
const getEmailHostname = newEmail.email.replace(/.*#/, "");
const blacklists = await BlackListModel.find({
hostname: new RegExp(".*" + getEmailHostname + ".*", "i")
});
if (blacklists.length > 0) {
logger.log({
level: "info",
message:
"A BLACKLIST ENTRY WAS TRYING TO SUBMIT AN APPLICATION"
});
return false;
}
const savedEmail = new ReceivedEmailModel(newEmail);
await savedEmail.save();
logger.log({
level: "info",
message:
"SAVED RECEIVED EMAIL =>" + JSON.stringify(savedEmail)
});
}
} catch (err) {
logger.log({ level: "error", message: err });
}
}); // msg on body
});
}); // on mail
this.imap.once("error", err => {
logger.log({
level: "error",
message: err
});
}); // on error
}); // openInbox
}); // ready
this.imap.connect();
} catch (err) {
logger.log({
level: "error",
message: err
});
}
}
close() {
if (this.imap) this.imap.end();
}
}
module.exports = MailListenerWrapper;
In app.js:
global.mailListenerWrapper = new mailListenerWrapper();
The receivedEmail.js model:
const mongoose = require("mongoose");
// Schema variable
const Schema = mongoose.Schema;
// Tags
const receivedMailSchema = new Schema(
{
title: {
type: String,
required: true
},
from: {
name: {
type: String
},
email: {
type: String
}
},
text: {
type: String
}
},
{
collection: "receivedEmail",
timestamps: true
}
);
const ReceivedEmail = mongoose.model("ReceivedEmail", receivedMailSchema);
module.exports = ReceivedEmail;
THE PROBLEM
The console log executes twice and the email is saved on my database twice, and does not save the address that it was sent from.
I have no idea why this could be happening. Could there be some way that the imap class is being instantiated twice?
I guess I'm pretty late, but maybe it could still be useful for anyone else.
I experienced this issue as well. But I realized that node-imap documetation specifies the use of .once() instead of .on() in the sample code.
Try to change the event below:
msg.on("body", async stream => {
....
}
To:
msg.once("body", async stream => {
....
}
It did work for me!
I am trying to create a simple event emitter, and when I attempt to test the emitter it is showing up undefined through jest.
Code for the Event Emitter:
class EventEmitter {
constructor() {
this.events = {};
}
on(e, fn) {
if (this.events[e]) {
return this.event[e].add(fn);
}
return this.events[e] = new Set([fn]);
}
once(e, fn) {
if (this.events[e]) {
this.event[e].add(fn, 1);
}
this.events[e] = new Set([fn, 1]);
}
emit(e, ...args) {
if (this.events[e]) {
this.events[e].forEach(fn => {
if (typeof fn === 'function')
fn.apply(null, args);
});
if (this.events[e].has(1)) {
delete this.events[e];
}
} else if (!this.events[e]) {
console.log('Event Argument does not exist - please enter a valid event');
}
}
off(e) {
if (arguments.length === 0) {
this.events = {};
}
if (this.events[e]) {
delete this.events[e];
} else if (!this.events[e]) {
return console.log('Event Argument does not exist - please enter a valid event');
}
}
}
Code for the testing:
const EventEmitter = require('../index.js');
// Creating new Event Emitter
test('should Emit named events with a single argument', () => {
const ee = new EventEmitter();
ee.on('multiple', (x, y) => {
console.log(`First Argument: ${x}, Second Argument: ${y}`);
});
ee.on('single', () => "Why isnt this working")
const res = console.log(ee.emit('single'))
expect(res).toBe('Why isnt this working')
})
const res is returning undefined, but i am not sure why - any help would be so appreciated!
I have a feathersjs service created using the feathers generate service command. I want to override its definition of create method.
This is my service class
/* eslint-disable no-unused-vars */
// Initializes the `userGroup` service on path `/usergroup`
const createService = require('feathers-sequelize');
const createModel = require('../../models/user-group.model');
const hooks = require('./user-group.hooks');
const filters = require('./user-group.filters');
const async = require('async');
module.exports = function () {
const app = this;
const Model = createModel(app);
const paginate = app.get('paginate');
const options = {
name: 'usergroup',
Model,
paginate,
create: fnCreateGroup // documentation says this allows you to create your own create method
};
function fnCreateGroup(data, params) {
let json = {
done: false
};
let permissionIds = Object.keys(data.permissionList), inIds = [];
for (let i in permissionIds) {
if (data.permissionList[permissionIds[i]]) {
inIds.push(parseInt(permissionIds[i]));
}
}
if (inIds.length === 0) {
json.cause = 'You must provide the permission List';
return Promise.resolve(json);
}
async.parallel([
function (cb) {
Model.create({
groupName: data.groupName
}).then(function (ug) {
cb(null, ug);
}, function (err) {
cb(err, null);
});
},
function (cb) {
app.models.permissions.findAll({
where: {
id: {
$in: inIds
}
}
}).then(function (plist) {
cb(null, plist);
});
}
]
, function (err, results) {
if (typeof err !== 'undefined' && err !== null) {
json.err = err;
return Promise.resolve(json);
} else {
let permissions = results[1], group = results[0];
for (let i = 0; i < permissions.length; i++) {
group.addPermission(permissions[i]);
}
json.done = true;
json.id = group.id;
return Promise.resolve(json);
}
});
}
// Initialize our service with any options it requires
app.use('/usergroup', createService(options));
// Get our initialized service so that we can register hooks and filters
let service = app.service('usergroup');
service.hooks(hooks);
if (service.filter) {
service.filter(filters);
}
};
The test on create method shows the result of original method and not mine.
What can I do?
How to override and extend existing services is documented in the database adapter common API. You can use hooks by setting hook.result or extend the existing ES6 class:
const Service = require( 'feathers-sequelize').Service;
class MyService extends Service {
create(data, params) {
data.created_at = new Date();
return super.create(data, params);
}
}
app.use('/todos', new MyService({
paginate: {
default: 2,
max: 4
}
}));
I have the following case: When I try to connect the module called 'Signaling-Server.js'
in the view of html the console says: GET ERROR [HTTP/1.1 400 Bad Request 1ms]
But this only happens when I add these Module. When I try to connect without him the socket.io connections works perfectly.
app.js
//Modules
var express = require("express"),
http = require("http"),
morgan= require("morgan"),
bodyParser = require('body-parser'),
methodOverride = require('method-override'),
app = express(),
server = http.createServer(app),
io = require("socket.io").listen(server);
app.use(express.static(__dirname + '/public'));
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({ extended:false}));
app.use(bodyParser.json());
app.use(methodOverride());
app.set("views",__dirname + "/views");
//I need to 'onnect with this module
//require('./Signaling-Server.js')(myServerOrPort);
require('./Signaling-Server.js')(server);
//Server is ready
server.listen(3000);
The code of Signaling-Server is here (Cortesy of MuazKhan Proyect "RTCMultiConnection")
Signaling-Server.js
// Muaz Khan - www.MuazKhan.com
// MIT License - www.WebRTC-Experiment.com/licence
// Documentation - github.com/muaz-khan/RTCMultiConnection
module.exports = exports = function(app, socketCallback) {
var io = require('socket.io').listen(app, {
log: false,
origins: '*:*'
});
io.set('transports', [
'websocket', // 'disconnect' EVENT will work only with 'websocket'
'xhr-polling',
'jsonp-polling'
]);
var listOfUsers = {};
var shiftedModerationControls = {};
var ScalableBroadcast;
io.sockets.on('connection', function(socket) {
var params = socket.handshake.query;
var socketMessageEvent = params.msgEvent || 'RTCMultiConnection-Message';
if (params.enableScalableBroadcast) {
if (!ScalableBroadcast) {
ScalableBroadcast = require('./Scalable-Broadcast.js');
}
var singleBroadcastAttendees = params.singleBroadcastAttendees;
ScalableBroadcast(socket, singleBroadcastAttendees);
}
socket.userid = params.userid;
listOfUsers[socket.userid] = {
socket: socket,
connectedWith: {},
isPublic: false, // means: isPublicModerator
extra: {}
};
socket.on('extra-data-updated', function(extra) {
try {
if (!listOfUsers[socket.userid]) return;
listOfUsers[socket.userid].extra = extra;
for (var user in listOfUsers[socket.userid].connectedWith) {
listOfUsers[user].socket.emit('extra-data-updated', socket.userid, extra);
}
} catch (e) {}
});
socket.on('become-a-public-moderator', function() {
try {
if (!listOfUsers[socket.userid]) return;
listOfUsers[socket.userid].isPublic = true;
} catch (e) {}
});
socket.on('get-public-moderators', function(userIdStartsWith, callback) {
try {
userIdStartsWith = userIdStartsWith || '';
var allPublicModerators = [];
for (var moderatorId in listOfUsers) {
if (listOfUsers[moderatorId].isPublic && moderatorId.indexOf(userIdStartsWith) === 0 && moderatorId !== socket.userid) {
var moderator = listOfUsers[moderatorId];
allPublicModerators.push({
userid: moderatorId,
extra: moderator.extra
});
}
}
callback(allPublicModerators);
} catch (e) {}
});
socket.on('changed-uuid', function(newUserId) {
try {
if (listOfUsers[socket.userid] && listOfUsers[socket.userid].socket.id == socket.userid) {
if (newUserId === socket.userid) return;
var oldUserId = socket.userid;
listOfUsers[newUserId] = listOfUsers[oldUserId];
listOfUsers[newUserId].socket.userid = socket.userid = newUserId;
delete listOfUsers[oldUserId];
return;
}
socket.userid = newUserId;
listOfUsers[socket.userid] = {
socket: socket,
connectedWith: {},
isPublic: false,
extra: {}
};
} catch (e) {}
});
socket.on('set-password', function(password) {
try {
if (listOfUsers[socket.userid]) {
listOfUsers[socket.userid].password = password;
}
} catch (e) {}
});
socket.on('disconnect-with', function(remoteUserId, callback) {
try {
if (listOfUsers[socket.userid] && listOfUsers[socket.userid].connectedWith[remoteUserId]) {
delete listOfUsers[socket.userid].connectedWith[remoteUserId];
socket.emit('user-disconnected', remoteUserId);
}
if (!listOfUsers[remoteUserId]) return callback();
if (listOfUsers[remoteUserId].connectedWith[socket.userid]) {
delete listOfUsers[remoteUserId].connectedWith[socket.userid];
listOfUsers[remoteUserId].socket.emit('user-disconnected', socket.userid);
}
callback();
} catch (e) {}
});
function onMessageCallback(message) {
try {
if (!listOfUsers[message.sender]) {
socket.emit('user-not-found', message.sender);
return;
}
if (!listOfUsers[message.sender].connectedWith[message.remoteUserId] && !!listOfUsers[message.remoteUserId]) {
listOfUsers[message.sender].connectedWith[message.remoteUserId] = listOfUsers[message.remoteUserId].socket;
listOfUsers[message.sender].socket.emit('user-connected', message.remoteUserId);
if (!listOfUsers[message.remoteUserId]) {
listOfUsers[message.remoteUserId] = {
socket: null,
connectedWith: {},
isPublic: false,
extra: {}
};
}
listOfUsers[message.remoteUserId].connectedWith[message.sender] = socket;
if (listOfUsers[message.remoteUserId].socket) {
listOfUsers[message.remoteUserId].socket.emit('user-connected', message.sender);
}
}
if (listOfUsers[message.sender].connectedWith[message.remoteUserId] && listOfUsers[socket.userid]) {
message.extra = listOfUsers[socket.userid].extra;
listOfUsers[message.sender].connectedWith[message.remoteUserId].emit(socketMessageEvent, message);
}
} catch (e) {}
}
var numberOfPasswordTries = 0;
socket.on(socketMessageEvent, function(message, callback) {
if (message.remoteUserId && message.remoteUserId === socket.userid) {
// remoteUserId MUST be unique
return;
}
try {
if (message.remoteUserId && message.remoteUserId != 'system' && message.message.newParticipationRequest) {
if (listOfUsers[message.remoteUserId] && listOfUsers[message.remoteUserId].password) {
if (numberOfPasswordTries > 3) {
socket.emit('password-max-tries-over', message.remoteUserId);
return;
}
if (!message.password) {
numberOfPasswordTries++;
socket.emit('join-with-password', message.remoteUserId);
return;
}
if (message.password != listOfUsers[message.remoteUserId].password) {
numberOfPasswordTries++;
socket.emit('invalid-password', message.remoteUserId, message.password);
return;
}
}
}
if (message.message.shiftedModerationControl) {
if (!message.message.firedOnLeave) {
onMessageCallback(message);
return;
}
shiftedModerationControls[message.sender] = message;
return;
}
if (message.remoteUserId == 'system') {
if (message.message.detectPresence) {
if (message.message.userid === socket.userid) {
callback(false, socket.userid);
return;
}
callback(!!listOfUsers[message.message.userid], message.message.userid);
return;
}
}
if (!listOfUsers[message.sender]) {
listOfUsers[message.sender] = {
socket: socket,
connectedWith: {},
isPublic: false,
extra: {}
};
}
// if someone tries to join a person who is absent
if (message.message.newParticipationRequest) {
var waitFor = 120; // 2 minutes
var invokedTimes = 0;
(function repeater() {
invokedTimes++;
if (invokedTimes > waitFor) {
socket.emit('user-not-found', message.remoteUserId);
return;
}
if (listOfUsers[message.remoteUserId] && listOfUsers[message.remoteUserId].socket) {
onMessageCallback(message);
return;
}
setTimeout(repeater, 1000);
})();
return;
}
onMessageCallback(message);
} catch (e) {}
});
socket.on('disconnect', function() {
try {
var message = shiftedModerationControls[socket.userid];
if (message) {
delete shiftedModerationControls[message.userid];
onMessageCallback(message);
}
} catch (e) {}
try {
// inform all connected users
if (listOfUsers[socket.userid]) {
for (var s in listOfUsers[socket.userid].connectedWith) {
listOfUsers[socket.userid].connectedWith[s].emit('user-disconnected', socket.userid);
if (listOfUsers[s] && listOfUsers[s].connectedWith[socket.userid]) {
delete listOfUsers[s].connectedWith[socket.userid];
listOfUsers[s].socket.emit('user-disconnected', socket.userid);
}
}
}
} catch (e) {}
delete listOfUsers[socket.userid];
});
if (socketCallback) {
socketCallback(socket);
}
});
};
Anybody knows whats the fix?
You can either try Ahmed's solution i.e. passing server object here:
require('./Signaling-Server.js') (server);
In your codes, the server object is using http.
I'll suggest trying this instead:
var fs = require('fs');
var options = {
key: fs.readFileSync('fake-keys/privatekey.pem'),
cert: fs.readFileSync('fake-keys/certificate.pem')
};
var express = require("express"),
http = require("https"), // Use HTTPs here -------------
app = express(),
server = http.createServer(options, app);
require('./Signaling-Server.js')(server);
You can either try valid SSL certificate keys or fake-keys.
Here is how to use valid certificates:
var options = {
key: fs.readFileSync('../ssl/private/domain.com.key'),
cert: fs.readFileSync('../ssl/certs/domain.com.crt'),
ca: fs.readFileSync('../ssl/certs/domain.com.cabundle')
};
In Express 3, you should pass the app object to socket.io not the server like in Express 2. Assuming you are using Express 3 and not 2. You just need to change one line to set up socket.io correctly
Try replacing this
require('./Signaling-Server.js')(server);
with this
require('./Signaling-Server.js')(app);