I was trying to implement the following code and got the TypeError error when I ran it.
app.js
var app = module.exports = require('express').createServer();
var io = require('socket.io').listen(app);
var path = require('path');
app.listen(3000);
app.get('/',function(req,res){
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function(socket){
socket.emit('welcome', {text: 'Welcome!!!'});
});
Error Output:
TypeError: Path must be a string. Received null
at assertPath (path.js:8:11)
at posix.join (path.js:479:5)
at exports.send (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/node_modules/connect/lib/middleware/static.js:129:20)
at ServerResponse.res.sendfile (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/response.js:186:3)
at /Users/rluo/Desktop/learn/learnNode/socket.io_epxress/app.js:8:6
at callbacks (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/router/index.js:272:11)
at param (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/router/index.js:246:11)
at pass (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/router/index.js:253:5)
at Router._dispatch (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/router/index.js:280:5)
at Object.Router.middleware [as handle] (/Users/rluo/Desktop/learn/learnNode/socket.io_epxress/node_modules/express/lib/router/index.js:45:10)
package.json:
{
"name":"socketio_express-example",
"version":"0.0.1",
"private":true,
"dependencies":{
"socket.io":"0.8.7",
"express":"2.5.4"
}
}
Thanks in advance.
Examples:
// assuming index.html is in the same directory as this script
res.sendFile(__dirname + '/index.html');
__dirname
Added in: v0.1.27
The name of the directory that the currently executing script resides in.for more detail https://nodejs.org/docs/latest/api/globals.html
check this thread TypeError: Path must be a string
Creating socket
var app = require('express')();
var http = require('http').Server(app);
Express initializes app to be a function handler that you can supply to an HTTP server (as seen in line 2). socket.io
__dirname vs path
Before you use res.sendFile() you need to set static files directory like below.
var express = require('express');
var app = express();
app.use(express.static(path.join(__dirname+'your index or static files location'));
app.get('/',function(req,res){
res.sendFile(__dirname+'index.html');
});
Please use the 'path' module that you have required. Try this:
app.get('/',function(req,res){
res.sendfile(path.join(__dirname, '/index.html'));
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With