使用Node中的Express.JS在req.path中读取UTF8字符

时间:2016-07-02 10:42:23

标签: node.js express path request

Express读取此请求路径 - /wiąz.txt/wiÄz.txt,我得到/wiÄz.txt doesn't exist,但wiąz.txt存在。是否可以在请求路径中读取utf8字符?

var express = require('express');
var fs = require('fs');
var app = express();
app.set('etag', false);
app.set('x-powered-by', false);

app.route('*').all(function(req, res) {
    res.set('Content-Type', 'text/plain');

    try {
        var file = fs.readFileSync('.' + req.path, 'utf8'); // req.path starts always with /, the result is ./FILE
        res.send(file);
    } catch (e) {
        res.send(req.path + " doesn't exist");
    }
});

app.listen(80, function () {
    console.log('HTTP Server is now running on port 80');
});

1 个答案:

答案 0 :(得分:1)

试试这个。

var file = fs.readFileSync('.' + decodeURIComponent(req.path), 'utf8');
res.send(file);