小错误:TypeError: Arguments to path.join must be strings, 求真相
发布于 10 年前 作者 ljgstudy 6050 次浏览 最后一次编辑是 8 年前

Node.js中的两个模块Socket.io 和Express做整合的时候出现了以下的错误: <pre><code> TypeError: Arguments to path.join must be strings at f (path.js:204:15) at Object.filter (native) at exports.join (path.js:209:40) at exports.send (E:\nodejs\demo\socket.io-express\node_modules\express\node_modules\connect\lib\middleware\static.js:129:20) at ServerResponse.res.sendfile (E:\nodejs\demo\socket.io-express\node_modules\express\lib\response.js:186:3) at io.sockets.on.socket.emit.text (E:\nodejs\demo\socket.io-express\app.js:8:6) at callbacks (E:\nodejs\demo\socket.io-express\node_modules\express\lib\router\index.js:272:11) at param (E:\nodejs\demo\socket.io-express\node_modules\express\lib\router\index.js:246:11) at pass (E:\nodejs\demo\socket.io-express\node_modules\express\lib\router\index.js:253:5) at Router._dispatch (E:\nodejs\demo\socket.io-express\node_modules\express\lib\router\index.js:280:5) </code></pre> 主要的原因是下面两段代码: 第一中写法: <pre><code> app.get(’/’, function(req, res){ res.sendfile(__dirname + ‘/index.html’); }); </code></pre> 第二种写法: <pre><code> app.get(’/’, function(req, res){ res.sendfile(’/index.html’, {root: __dirname}); }); </code></pre> 用第一段代码会出错,改成第二种写法就没问题了。 这是怎么个情况呢,求真相。。。

11 回复

嗯, 看 send 模块 (sendfile 的依赖包)

https://github.com/visionmedia/send

在win 下 你传

__dirname + '/index.html' -> E:\nodejs\demo/index.html

貌似,那里用 url 解析模块.最后解析的结果不是windows 那种路径样子…

然后到创建流的时候路径就不对了…

我只用了express和socket.io模块,send模块包含在express中了?

@ljgstudy

肯定啊… …

你看一下express 3.x 的package.json

@youxiachai 感谢大神指点!!!

__dirname + '/index.html' 这句改成 path.join(__dirname, '/index.html') 应该就可以了吧?

@alsotang windows下还是同样的问题。。。

@ljgstudy

//path.join(__dirname, '/index.html')

path.join(__dirname, 'index.html')

試試不用那個’/’

@mondwan 同样的问题,估计和windows的路径是反斜线 ("/") 有关系

@ljgstudy 嗯... 我發現你應該在用2.0 的express connect 用的應該是1.x 根源 https://github.com/senchalabs/connect/blob/1.x/lib/middleware/static.js#L104

root = options.root ? normalize(options.root) : null

https://github.com/senchalabs/connect/blob/1.x/lib/middleware/static.js#L129

path = normalize(join(root, path));

不設定root 就是null, join(null, path) => errors

@mondwan 说的对。我刚才验证了一把,结果如下: <code>root = null; path = E:\nodejs\demo\sending-nickname\index.html</code> 然后执行 <code> path = normalize(join(root, path));</code> 出错,与windows路径分隔符无关! 谢谢,长知识了。。。

@ljgstudy 额。。。楼上说了那么多,你就始终不能自己打印 path.join(__dirname, ‘/index.html’) 出来看看吗。。

回到顶部