锋言锋语

NferZhuang的自留地

Path must be a string. Received xxx

问题表现

var path = require('path');

var pwd = __dirname;
var path1 = 123;
var path2 = '456';
console.log( path.join(pwd, path1) );
console.log( path.join(pwd, path2) );

上述代码运行报错:

TypeError: Path must be a string. Received 123 at Object.<anonymous> test.js:6:19)

问题分析

path.join()函数的定义如下:

path.join([…paths])

…paths <String> A sequence of path segments

这里强调了,paths参数的类型必须是String,因此path1作为Number类型肯定不满足条件。

问题解决

使用Number.prototype.toString()讲Number类型转换为String类型:

var path = require('path');

var pwd = __dirname;
var path1 = 123;
var path2 = '456';
// console.log( path.join(pwd, path1) );
// console.log( path.join(pwd, path2) );
console.log( path.join(pwd, path1.toString()) );
console.log( path.join(pwd, path2.toString()) );
文 / nfer
LEAVE A REPLY

loading