【问题标题】:Efficient way to read file in NodeJS在 NodeJS 中读取文件的有效方法
【发布时间】:2018-04-15 04:57:47
【问题描述】:

我正在接收从 Ajax 请求发送的图像文件:

var data = canvas.toDataURL('image/jpg', 1.0);
$.post({
  url: "/upload-image",
  data: { 
    file: data
  }
}).done(function(response) {
  ....
})

}

在服务器端,我想将图像文件传输到 API

function getOptions(buffer) {
  return {
    url: '.../face_detection',
    headers: headers,
    method: 'POST',
    formData: {
      filename: buffer
    }
  }
}

router.post('/upload-image', function(req, res, next) {

  console.log('LOG 0' + Date.now());

  var data_url = req.body.file;
  var matches = data_url.match(/^data:.+\/(.+);base64,(.*)$/);
  var ext = matches[1];
  var base64_data = matches[2];
  var buffer = new Buffer(base64_data, 'base64');

  console.log('LOG 1' + Date.now());

  request(getOptions(buffer), function(error, response, body) {
    res.json(body);
    console.log(Date.now());
  });
});

我遇到的问题是 LOG 0 和 LOG 1 之间的线路非常慢,只有几秒钟。但是图像只有650kb。有没有办法加快这一进程?

使用另一种方法读取header,避开缓冲区,改变上传过程。我不知道,但我想更快。

非常感谢。

【问题讨论】:

  • 您能看到实际花费最多的时间吗?是 RegEx 还是 Buffer 创建?如果是 Buffer 创建,测试一下Buffer.from() 是否性能更高。另外,尝试在production mode 中运行 node.js。
  • 它是慢的正则表达式......我应该搜索它
  • 那我试试这个模块,看看你能不能加快速度。查看它的来源以获得一些想法:data-uri-to-buffer.
  • 这解决了我的问题,非常感谢。但我不知道如何检索文件的扩展名。我让你回答这个问题:)
  • 看我的回答。我添加了一个示例,说明如何使用上面链接的模块以及如何查找扩展名/MIME。

标签: node.js express fs


【解决方案1】:

我建议使用库来处理其中的一些逻辑。如果您希望保留一个精简的依赖项列表,您可以查看其中一些模块的来源,并以此为基础制定您自己的解决方案。

我特别推荐 file-type 解决方案。确保 Buffer 是哪种文件的一种更安全(不能说是最安全)的方法是检查文件的各个方面。 file-type 似乎至少看一下文件的Magic Number 来检查类型。并非万无一失,但如果您接受来自用户的文件,则必须接受所涉及的风险。

还可以查看安全堆栈交换问题以了解良好做法。虽然下面说的是 PHP,但所有服务器软件都存在易受用户输入影响的风险:


"use strict";

const dataUriToBuffer = require('data-uri-to-buffer'),
    fileType = require("file-type"),
    express = require("express"),
    router = express.Router(),
    util = require("util"),
    fs = require("fs"),
    path = require("path");

const writeFileAsync = util.promisify(fs.writeFile);

// Keep track of file types you support
const supportedTypes = [
    "png",
    "jpg",
    "gif"
];

// Handle POSTs to upload-image
router.post("/upload-image", function (req, res, next) {
    // Did they send us a file?
    if (!req.body.file) {
        // Unprocessable entity error
        return res.sendStatus(422);
    }

    // Get the file to a buffer
    const buff = dataUriToBuffer(req.body.file);

    // Get the file type
    const bufferMime = fileType(buff); // {ext: 'png', mime: 'image/png'}

    // Is it a supported file type?
    if (!supportedTypes.contains(bufferMime.ext)) {
        // Unsupported media type
        return res.sendStatus(415);
    }

    // Save or do whatever with the file
    writeFileAsync(path.join("imageDir", `userimage.${bufferMime.ext}`), buff)
        // Tell the user that it's all done
        .then(() => res.sendStatus(200))
        // Log the error and tell the user the save failed
        .catch((err) => {
            console.error(err);
            res.sendStatus(500);
        });
});

【讨论】:

    猜你喜欢
    • 2019-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多