I am using Node.js and I'm trying to get PubNub integrated to get my chatroom up and running. I have been following numerous tutorials and they all seem to have PubNub executing from their client-side. However, to ensure the security of my publish-key and subscribe-key I want to have PubNub execute from my server-side (Nodejs). However the problem is occurs exactly when I try to do just that. Here is my server:
var express = require('express');
var path = require('path');
var bodyParser = require('body-parser');
var request = require('request');
var pubnub = require('pubnub');
pubnub = pubnub.init({
subscribe_key: 'sub-c-demo',
publish_key: 'pub-c-demo',
ssl: true
});
//Defining routes
var routes = require('./routes/index');
//Init express
var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
//View Engine
app.set('view engine', 'ejs');
//Set Static Folder
app.use(express.static(path.join(__dirname, 'public')));
//Get route
app.use('/', routes);
//Set Port
app.set('port', (process.env.PORT || 3000));
app.listen(app.get('port'), function(){
console.log('3000 is the magic port!!');
});
TypeError: pubnub.init is not a function
$ node server
/Users/macbookpro/Desktop/project007/server.js:8
var pubnub = pubnub.init({
^
TypeError: pubnub.init is not a function
at Object.<anonymous> (/Users/macbookpro/Desktop/project007/server.js:8:21)
at Module._compile (module.js:573:32)
at Object.Module._extensions..js (module.js:582:10)
at Module.load (module.js:490:32)
at tryModuleLoad (module.js:449:12)
at Function.Module._load (module.js:441:3)
at Module.runMain (module.js:607:10)
at run (bootstrap_node.js:382:7)
at startup (bootstrap_node.js:137:9)
at bootstrap_node.js:497:3
npm i pubnub --save
var pubnub = require('pubnub');
https://cdn.pubnub.com/sdk/javascript/pubnub.4.4.2.min.js
<script src="js/pubnubchatroom.js"></script>
There is a new way to initialize your PubNub SDK. See the following example. v4 SDKs are not drop-in compatible. You can mix v4 and v3 SDKs between environments successfully.
const PubNub = require('pubnub');
const pubnub = new PubNub({
publishKey : 'demo',
subscribeKey : 'demo'
})