Peter Bennett Peter Bennett - 2 months ago 17
Javascript Question

NodeJS - TypeError: app.listen is not a function

I know this question kind of already exists, but they answers did not rectify my problem.

The error is "TypeError: app.listen is not a function";

My full code is below, thanks in advance. (PS, I do not have anything running on the same port)

var io = require('socket.io')(app);
var fs = require('fs');
var serialPort = require("serialport");

var app = require('http');

app.createServer(function (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
res.writeHead(200);
res.end(data);
});
}).listen(1337, '127.0.0.1');


var port = new serialPort(process.platform == 'win32' ? 'COM3' : '/dev/ttyUSB0', {
baudRate: 9600
});

port.on( 'open', function() {
console.log('stream read...');
});

port.on( 'end', function() {
console.log('stream end...');
});

port.on( 'close', function() {
console.log('stream close...');
});

port.on( 'error', function(msg) {
console.log(msg);
});

port.on( 'data', function(data) {
console.log(data);

var buffer = data.toString('ascii').match(/\w*/)[0];
if(buffer !== '') bufferId += buffer;

clearTimeout(timeout);
timeout = setTimeout(function(){
if(bufferId !== ''){
id = bufferId;
bufferId = '';
socket.emit('data', {id:id});
}
}, 50);
});

io.on('connection', function (socket) {
socket.emit('connected');
});

app.listen(80);

Answer

the error come from this line :

app.listen(80);

Since app is your http module var app = require('http');, you were trying to listen to the node http module (and well you can't). You need to create a server with this http module and then listen to it.

This is what you did with those lines :

app.createServer(function (req, res) {
    fs.readFile(__dirname + '/index.html',
        function (err, data) {
            res.writeHead(200);
            res.end(data);
        });
}).listen(1337, '127.0.0.1');

Basically, http.createServer() returns a http.server instance. This instance has a listen method that causes the server to accept connections on the specified port.

So this can work :

var app = require('http');
app.createServer().listen(8080);

this can't :

var app = require('http');
app.listen(8080);

The http module documentation : https://nodejs.org/api/http.html#http_http_createserver_requestlistener