【问题标题】:Lstat: Type error: path must be a string.Lstat:类型错误:路径必须是字符串。
【发布时间】:2014-04-26 11:02:00
【问题描述】:

这是我的代码:


var http = require('http');
var port = process.env.port || 1337;
var fs = require('fs');
var url = require('url');

var current_data_store = __dirname.replace(/\\/g,"/")+"/DATA";

http.createServer(function (req, res) {
    res.writeHead(200, { 'Content-Type': 'text/plain' });

    this.requiredPath = current_data_store+""+url.format(req.url);
    console.log(this.requiredPath);
    fs.exists(this.requiredPath, function (exists) {
        if(exists){
            if(fs.lstatSync(this.requiredPath).isDirectory()){
                console.log("It's dir");
                //render list of files
            } else if(fs.lstatSync(this.requiredPath).isFile()){
                console.log("It's file");
                //render file
            }
        } else {
            console.log("doesnt exist");
        }
    });

    res.end('Hello World\n'+req.url+'');
}).listen(port);

我想做一个简单的文件浏览器。脚本将显示地址栏中输入的路径中的文件(但仅显示 DATA 文件中的文件)。

问题是:节点返回错误:

fs.js:679 返回 binding.lstat(pathModule._makeLong(path)); ^ TypeError:路径必须是字符串 在 Object.fs.lstatSync (fs.js:679:18) 在 C:\Users\piotr_000\Source\Repos\Cloud\Cloud\server.js:15:19 在 Object.cb [as oncomplete] (fs.js:168:19)

我真的不知道它为什么会出现。 fs.exists() 函数正常工作,不会抱怨路径不是字符串。

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    您在fs.exists() 回调中使用this,这与父范围中的this 不同。试试这个:

    this.requiredPath = current_data_store+""+url.format(req.url);
    console.log(this.requiredPath);
    var self = this;
    fs.exists(this.requiredPath, function (exists) {
        if(exists){
            if(fs.lstatSync(self.requiredPath).isDirectory()){
                console.log("It's dir");
                //render list of files
            } else if(fs.lstatSync(self.requiredPath).isFile()){
                console.log("It's file");
                //render file
            }
        } else {
            console.log("doesnt exist");
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2017-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-23
      • 2017-04-23
      相关资源
      最近更新 更多