没有明确

时间:2017-08-28 09:04:39

标签: node.js express

var http = require('http');
var fs = require('fs');
var path="";
process.stdin.on('data', function(chunk) {      
    var buffer = new Buffer(chunk);
    path = buffer.toString();    
    path = path.replace("\n","");
    path = path.replace("\r","");
});
var str="";
var fileRead;
var arrayFiles = [];
function onRequest(request, response) {
    str = "";    
    if (request.url === '/favicon.ico') {
        response.writeHead(200, {'Content-Type': 'image/x-icon'});
        response.end();
        return;
    } else if (request.url === '/index.html') {
        console.log("Request received" + path);
        fs.readdir(path, function(err, items) {
        console.log(items);
        arrayFiles = [];
        str += items;
        arrayFiles.push(items);            
        console.log("Enter file to be read"); 
        process.stdin.on('data', function(chunk) {
            var buffer = new Buffer(chunk);
            fileRead = buffer.toString();
            fileRead = fileRead.replace("\n","");
            fileRead = fileRead.replace("\r","");
            if(arrayFiles[0].indexOf(fileRead) != -1) {
                fs.readFile(fileRead, 'utf8', function(err, contents) {
                    response.writeHead(200, {"Context-Type": "text/plain"});
                    response.write(contents);
                    response.end();
                });
            }
        });
    });
} 
}
http.createServer(onRequest).listen(8000);

给定程序显示作为输入给出的目录中的文件。然后输入要显示其内容的文件名。

在给定的程序中,我需要使用GET请求从用户输入文件的名称,而不是从stdin读取值。没有快递模块可以做到这一点。如果是,请帮助。

提前致谢

1 个答案:

答案 0 :(得分:0)

是的,您可以使用普通的Node.js http代码检索从HTTP GET请求发送的文件名,而不需要任何Express内容。

方法是:将filename作为URL参数传递,并在服务器端解析。这是一个例子:

const http = require('http');
const server = http.createServer((req, res) => {
  let params = req.url.substring(req.url.lastIndexOf('?') + 1).split('&');
  let filename = null;
  for (let p of params) {
    let paramKeyValPair = p.split('=');
    if (paramKeyValPair[0] === 'filename') {
      filename = paramKeyValPair[1];
      break;
    }
  }
  console.log(filename);
  // deal with filename
  res.end('Hello');
}).listen(8327);

对于/index.html?filename=test.txt这样的网址,服务器端的filename变量为test.txt