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');
})
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 have the following code in a script.js file:
var express = require('express'),
app = express(),
cons = require('consolidate'),
MongoCl = require('mongodb').MongoClient,
Server = require('mongodb').Server;
app.engine('html', cons.swig);
app.set('view engine', 'html');
app.set('views', __dirname +'/views');
var mongoclient = new MongoCl( new Server('localhost', 27017, {'native_parser' : true}));
var db = mongoclient.db('course');
app.get('/', function (req,res) {
db.collection('hello_mongo_express').findOne({}, function (err, doc) {
res.render('hello',doc);
});
});
app.get('*', function (req,res) {
res.send('Page not found',404);
});
mongoclient.open(function (err, mongoclient) {
if(err) throw err;
var port = 8080;
app.listen(port);
console.log("Express server started on port "+port);
});
./views/hello.html looks like :
<h1>Hello, {{name}}</h1>
I have a valid collection within a db 'course'.
When I try running using node, I face the following issue:
F:\mongo_proj>node script.js
F:\mongo_proj\script.js:11
var db = mongoclient.db('course');
^
TypeError: mongoclient.db is not a function
at Object.<anonymous> (F:\mongo_proj\script.js:11:22)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3
Even though, I guess all the code that creates the mongoclient, db objects, will get called only when the db connectivity is been established. So what could the issue be
edit:
I tried #jerry's suggestion:
try this.. this simple way of connection
var MongoClient = require('mongodb').MongoClient
, assert = require('assert');
// Connection URL
var url = 'mongodb://localhost:27017/myproject';
// Use connect method to connect to the Server
MongoClient.connect(url, function(err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
db.close();
});
refer this link and try this
https://www.npmjs.com/package/mongodb
This issue is coming because, you are trying to use mongoclient before it opens connection. So wrap the code in open function as follow:
var db;
mongoclient.open(function (err, mongoclient) {
db = mongoclient.db('course');
if(err) throw err;
var port = 8080;
app.listen(port);
console.log("Express server started on port "+port);
});
See the link for further reference mongo connection
Also this .open() method is used in older versions. With newer version use .connect() method instead. For later versions may be refer this node driver manual
I am learning Node.js. I just found about module.exports. It seems to me that this is a way to help keep code clean and maintainable by separating code.
I tried out a few examples and it works. I got to console.log a few things by calling the method and it ran the function that was on another file.
I also learned some socket.io. I have got it to work as well.
I wanted to separate the code so I put all the socket.io connection information in a separate file and called the method on the main server file.
It doesn't work. The only way everything works if all the code is on the same page.
This is what I have:
app.js
var app = require('express')();
var ioConnect = require('./ioConnect.js')
var server = require('http').Server(app);
var io = require('socket.io')(server);
server.listen(80);
ioConnect.ioConnection();
ioConnect.js
function addScore() {
var io = require('socket.io');
io.on('connection', function(socket) {
socket.on('score', function(data) {
socket.emit('addScore', 15);
});
});
}
module.exports.ioConnection = addScore;
At first I got an error that said: "io is not defined" so I added
var io = require('socket.io)(server); and got server is not defined so I tried
var io = require('socket.io'); and got this error:
/root/game/ioConnect2.js:5
io.on('connection', function(socket) {
^
TypeError: Object function Server(srv, opts){
if (!(this instanceof Server)) return new Server(srv, opts);
if ('object' == typeof srv && !srv.listen) {
opts = srv;
srv = null;
}
opts = opts || {};
this.nsps = {};
this.path(opts.path || '/socket.io');
this.serveClient(false !== opts.serveClient);
this.adapter(opts.adapter || Adapter);
this.origins(opts.origins || '*:*');
this.sockets = this.of('/');
if (srv) this.attach(srv, opts);
} has no method 'on'
at Object.addScore [as ioConnection] (/root/game/ioConnect2.js:5:16)
at Object.<anonymous> (/root/game/app:8:19)
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
If I put the code together on one file everything works. Can someone please explain to me exactly whats going on here and what I need to do?
When you require socket.io it returns a function. In app.js you called that require/function with an argument and stored the return value in 'io'. Good so far. In ioConnect.js you are storing the function itself in io. rather than do that, you should pass the io you set in app.js to the function returned by your require of ioConnect.js.
app.js
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var ioConnect = require('./ioConnect.js')(io);
server.listen(80);
ioConnect.addScore();
ioConnect.js
function ioConnection(io) {
if (!(this instanceof ioConnection)) {
return new ioConnection(io);
}
this.io = io;
}
ioConnection.prototype.addScore = function() {
this.io.on('connection', function (socket) {
socket.on('score', function (data) {
socket.emit('addScore', 15);
});
});
}
module.exports = ioConnection;
I've check such kind of issue. but i don't find any. if you found it. just let me know.
I just getting started write javascript through node.js, and serialport. cand someone explain me why this error appear?
/Applications/MAMP/htdocs/homeautomation/server.js:42
var sp = new serialPort(portName, {
^
TypeError: undefined is not a function
at Object.<anonymous> (/Applications/MAMP/htdocs/homeautomation/server.js:42:10)
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
this is my starting code
/*
* dependencies
*/
var express = require('express'),
server = require('http').createServer(app),
io = require('socket.io').listen(server),
serialPort = require('serialport').serialPort;
server.listen(3000);
console.log('listen on port 3000')
/*
* Express
*/
var app = express();
// serve static files from index
app.configure(function(){
app.use(express.static(__dirname + '/'));
});
// respon to web GET request on index.html
app.get('/', function (req, res){
res.sendfile(__dirname + '/index.html');
});
/*
* Serial Port Setup
*/
var portName = '/dev/tty.usb.serial-A501JUTF';
//var portName = '/dev/tty.usbmodem1421';
var readData = ''; //Array to hold the values read from the port
var sp = new serialPort(portName, {
baudRate : 9600,
dataBits : 8,
parity : 'none',
stopBits: 1,
flowControl : false,
});
any help will be appreciated.
Your code is correct, except that you used the serialPort object of the require('serialport') library, when it's in fact SerialPort that you need to use, hence the undefined is not a function error that you encountered.
var SerialPort = require("serialport")
console.log(SerialPort.serialPort); // undefined
console.log(SerialPort.SerialPort); // { [Function: SerialPort, ... }
See the documentation for a sample usage.
Try this. It works perfectly.
var SerialPort = require('serialport');
var serialPort = SerialPort.serialPort;
var sp = new SerialPort("/dev/ttyACM0", {
});
I'm new to nodejs/expressjs. Could someone please explain how to to serve a page over https?
I have to ask this question another way, stackoverflow is complaining that my post is mainly code?
Here is the error dump:
app.get('/', function(request, response) {
^
TypeError: Object # has no method 'get' at Object.
(/home/john/startup/docm/w2.js:21:5) 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
And here is the code:
var express = require('express');
var fs = require('fs');
var app = express();
var options = {
ca: fs.readFileSync('csr.pem'),
cert: fs.readFileSync('cert.pem'),
key: fs.readFileSync('key.pem')
};
var server = require('https').createServer(options);
var portNo = 8889;
var app = server.listen(portNo, function() {
console.log((new Date()) + " Server is listening on port " + 8888);
});
app.get('/', function(request, response) {
app.use(express.static(__dirname));
console.log('app.get slash');
var buf = new Buffer(fs.readFileSync('index1.html'), 'utf-8');
response.send(buf.toString('utf-8'));
});
I'm new to nodejs/expressjs. Could someone please explain how to to serve a page over https?
The problem with your application is that you're overriding your Express instance with your HTTPS instance. This is how it is properly done:
var fs = require('fs');
var express = require('express');
var app = express();
var https = require('https');
var options = {
ca: fs.readFileSync('csr.pem'),
cert: fs.readFileSync('cert.pem'),
key: fs.readFileSync('key.pem')
};
var server = https.createServer(options, app);
server.listen(443, function() {
console.log((new Date()) + ' Server is listening on port 443');
});
app.use(express.static(__dirname));
app.get('/', function(req, res) {
console.log('app.get slash');
var file = fs.readFileSync('index1.html', {encoding: 'utf8'});
res.send(file);
});
These were the errors in your code:
Instead of passing Express to HTTPS you overwrote Express with the HTTPS instance.
You did not pass your Express application to your HTTPS instance.
The Express static() middleware should be served outside of specific request handlers.
You passed a buffer to another buffer to set its encoding although readFileSync() already has an encoding option.