gpt4 book ai didi

javascript - Node.js:从请求中获取路径

转载 作者:IT老高 更新时间:2023-10-28 21:53:12 27 4
gpt4 key购买 nike

我有一个名为“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);
});
};

最佳答案

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

我没有测试过你的代码,但是其他的东西可以用

如果你想从请求url获取路径信息

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

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

2.如果你有很大的文件夹结构,你想使用 node 来托管,那么我建议你使用一些框架,比如 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/

关于javascript - Node.js:从请求中获取路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18931452/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com