简体   繁体   中英

Lstat: Type error: path must be a string.

This is my code:


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);

I want to make simple file explorer. Script will show files from path typed in adress bar (but only files that are in DATA file).

The problem is: node return error:

fs.js:679 return binding.lstat(pathModule._makeLong(path)); ^ TypeError: path must be a string at Object.fs.lstatSync (fs.js:679:18) at C:\\Users\\piotr_000\\Source\\Repos\\Cloud\\Cloud\\server.js:15:19 at Object.cb [as oncomplete] (fs.js:168:19)

I really don't know why it appears. fs.exists() function works properly and don't complains that the path isn't a string.

You're using this inside your fs.exists() callback which is not the same as this in the parent scope. Try this instead:

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");
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM