.NET服務將* .gz文件導出到nodejs服務器。這些文件是gziped json字符串。Javascript從節點/快遞服務器讀取gz文件
這是本地保存文件的節點路由。
router.post("/", function (req, res) {
var filePath = path.join(__dirname, "../public", "data", req.header("filename"));
var writeStream = fs.createWriteStream(filePath);
req.pipe(writeStream);
req.on("end", function() {
writeStream.close();
res.sendStatus(200);
});
});
現在我在我的公共/數據目錄中有.gz文件。
我要求從客戶端JS那樣的文件:
static fetchJsonFile(path:string, callback:Function):void {
let httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === 4) {
if (httpRequest.status === 200) {
let data = JSON.parse(httpRequest.response);
if (callback)
callback("OK", data);
}
else if (httpRequest.status === 404) {
if (callback)
callback("Resource not found", null);
}
}
};
httpRequest.open("GET", path, true);
httpRequest.responseType = "json";
httpRequest.send();
}
它不工作 - 回報httpRequest.response == NULL。然而,服務器日誌顯示文件送達:GET /data/EURUSD1440.gz 200 1.352 ms - 322044
編輯當我設置httpRequest.responseType
等於"text"
,該httpRequest.response
接收壓縮的文件,不能被解析。
如何讓客戶端讀取,解壓縮和解析gzip文件?
我嘗試了很多變種都沒有成功。我的一些嘗試的:
連接並連接,用gzip靜態:
connect().use(gzipStatic(path.join(__dirname, "public")));
隨着fs
在routes/data.js
:
router.get("/", function (req, res) {
var filePath = path.join(__dirname, "../public", "data", req.header("filename"));
console.log(filePath);
var readStream = fs.createReadStream(filePath);
res.setHeader("Content-Type", "application/json");
res.setHeader("Content-Encoding", "gzip");
res.setHeader("Vary", "Accept-Encoding");
res.setHeader("Content-Disposition","gzip");
readStream.on("open", function() {
readStream.pipe(res);
});
readStream.on("end", function() {
readStream.close();
console.log("there will be no more data.");
});
readStream.on("error", function(err) {
res.end(err);
});
});
不幸的是,我沒有成功。有任何想法嗎?
編輯
它看起來像我無法正確設置響應頭沙爹內容被gzip壓縮。我的服務器主循環看起來像這樣:
"use strict";
var debug = require("debug")("Ea_Studio:server");
var http = require("http");
var express = require("express");
var path = require("path");
var favicon = require("serve-favicon");
var logger = require("morgan");
var bodyParser = require("body-parser");
var fs = require("fs");
var routes = require("./routes/index");
var data = require("./routes/data");
var app = express();
app.use(logger("dev"));
app.use(favicon(path.join(__dirname, "public", "favicon.ico")));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));
app.use(express.static(path.join(__dirname, "public")));
// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "jade");
app.use("/", routes);
app.use("/data", data);
它看起來像GET請求不被routes/data.js
如果文件在'public'中,那麼'express.static'中間件會處理它,因爲它是第一個。 – Prinzhorn
我明白了,但我無法以任何方式解決。 –