小编典典

Node.js:从请求获取路径

node.js

我有一个名为“ localhost:3000 / returnStat”的服务,该服务应将文件路径作为参数。例如“
/BackupFolder/toto/tata/titi/myfile.txt”。

如何在浏览器上测试此服务?例如,如何使用Express格式化此请求?

exports.returnStat = function(req, res) {

var fs = require('fs');
var neededstats = [];
var p = __dirname + '/' + req.params.filepath;

fs.stat(p, function(err, stats) {
    if (err) {
        throw err;
    }
    neededstats.push(stats.mtime);
    neededstats.push(stats.size);
    res.send(neededstats);
});
};

阅读 741

收藏
2020-07-07

共1个答案

小编典典

var http = require('http');
var url  = require('url');
var fs   = require('fs');

var neededstats = [];

http.createServer(function(req, res) {
    if (req.url == '/index.html' || req.url == '/') {
        fs.readFile('./index.html', function(err, data) {
            res.end(data);
        });
    } else {
        var p = __dirname + '/' + req.params.filepath;
        fs.stat(p, function(err, stats) {
            if (err) {
                throw err;
            }
            neededstats.push(stats.mtime);
            neededstats.push(stats.size);
            res.send(neededstats);
        });
    }
}).listen(8080, '0.0.0.0');
console.log('Server running.');

我尚未测试您的代码,但其他方法可行

如果您想从请求网址获取路径信息

 var url_parts = url.parse(req.url);
 console.log(url_parts);
 console.log(url_parts.pathname);

1.如果您获取的URL参数仍然无法读取文件,请在我的示例中更正您的文件路径。如果将index.html与服务器代码放在同一目录中,它将起作用…

2.如果您要使用节点托管大型文件夹结构,则建议您使用expressjs等框架

如果您想要原始解决方案的文件路径

var http = require("http");
var url = require("url");

function start() {
function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write("Hello World");
    response.end();
}

http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}

exports.start = start;

来源:http :
//www.nodebeginner.org/

2020-07-07