有没有办法在服务器上读取文件而无需在节点js中下载?

时间:2017-03-26 18:13:00

标签: javascript node.js parsing xlsx file-read

我想读取多个文件,现在我正在下载到本地并阅读,但我想知道是否有任何方法通过直接连接到服务器来读取或解析.xlsx文件?

2 个答案:

答案 0 :(得分:0)

试试这里......这应该适用于你所要求的内容以及更多内容。

xlsx

您应该能够读取服务器上的文件,解析它,获取您想要的信息而无需下载到硬盘驱动器。

答案 1 :(得分:0)

我想回答上面的问题,我最终使用了下面的方法,因为我遇到了同样的情况。

// Requiring modules
const http = require("http");
const fs = require("fs");
const path = require("path");
const url = require("url");

// Creating server to accept request
http.createServer((req, res) => {

    // Parsing the URL
    var request = url.parse(req.url, true);

    // Extracting the path of file
    var action = request.pathname;

    // Path Refinements
    var filePath = path.join(__dirname,
            action).split("%20").join(" ");

    // Checking if the path exists
    fs.exists(filePath, function (exists) {

        if (!exists) {
            res.writeHead(404, {
                "Content-Type": "text/plain" });
            res.end("404 Not Found");
            return;
        }

        // Extracting file extension
        var ext = path.extname(action);

        // Setting default Content-Type
        var contentType = "text/plain";

        // Checking if the extention of
        // image is '.png'
        if (ext === ".png") {
            contentType = "image/png";
        }

        // Setting the headers
        res.writeHead(200, {
            "Content-Type": contentType });

        // Reading the file
        fs.readFile(filePath,
            function (err, content) {
                // Serving the image
                res.end(content);
            });
    });
})

// Listening to the PORT: 3000
.listen(3000, "127.0.0.1");