跳到主要内容
CNode

小错误:TypeError: Arguments to path.join must be strings, 求真相

社区
Lljgstudy发布于 12 年前最后回复 12 年前
1170780

Node.js中的两个模块Socket.io 和Express做整合的时候出现了以下的错误:


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)

主要的原因是下面两段代码: 第一中写法:


app.get('/', function(req, res){
    res.sendfile(__dirname + '/index.html');
});
 

第二种写法:


app.get('/', function(req, res){
	res.sendfile('/index.html', {root: __dirname});
});

用第一段代码会出错,改成第二种写法就没问题了。 这是怎么个情况呢,求真相。。。

查看回复

回复 (11)

A
alsotang#1112 年前
引用 youxiachai嗯, 看 send 模块 (sendfile 的依赖包) https://github.com/visionmedia/send 在win 下 你传 dirname + '/index.htm...

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

L
ljgstudy#1012 年前
引用 youxiachai嗯, 看 send 模块 (sendfile 的依赖包) https://github.com/visionmedia/send 在win 下 你传 dirname + '/index.htm...

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

M
mondwan#912 年前
引用 youxiachai嗯, 看 send 模块 (sendfile 的依赖包) https://github.com/visionmedia/send 在win 下 你传 dirname + '/index.htm...

@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

L
ljgstudy#812 年前
M
mondwan#712 年前
引用 youxiachai嗯, 看 send 模块 (sendfile 的依赖包) https://github.com/visionmedia/send 在win 下 你传 dirname + '/index.htm...

@ljgstudy

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

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

試試不用那個'/'

A
alsotang#512 年前
引用 youxiachai嗯, 看 send 模块 (sendfile 的依赖包) https://github.com/visionmedia/send 在win 下 你传 dirname + '/index.htm...

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

Y
youxiachai#112 年前

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

https://github.com/visionmedia/send

在win 下 你传

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

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

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

参与回复

登录后即可参与回复。登录