Node.js:从请求中获取路径 [英] Node.js: get path from the request

查看:310
本文介绍了Node.js:从请求中获取路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a service called "localhost:3000/returnStat" that should take a file path as parameter. For example '/BackupFolder/toto/tata/titi/myfile.txt'.

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

How can I test this service on my browser? How can I format this request using Express for instance?

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


推荐答案

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

我没有测试过您的代码,但其他工作正常

I have not tested your code but other things works

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

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

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

1.If you are getting the URL parameters still not able to read the file just correct your file path in my example. If you place index.html in same directory as server code it would work...

2.如果您想要使用节点托管大文件夹结构,那么我会建议你使用像expressjs这样的框架

2.if you have big folder structure that you want to host using node then I would advise you to use some framework like 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/

这篇关于Node.js:从请求中获取路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆