使用node.js fs.writeFile写入二进制数据来创建镜像文件 [英] Writing binary data using node.js fs.writeFile to create an image file

查看:87
本文介绍了使用node.js fs.writeFile写入二进制数据来创建镜像文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 node.js fs.writeFile 作为二进制文件.JPEG 文件,但文件写入后我可以看到文件存储为纯文本,而不是二进制数据.

I'm trying to write a canvas data with node.js fs.writeFile as a binary. JPEG file, but after the file is written I can see that the file is stored as plain text, not binary data.

这是从客户端发送到我的节点的 data 示例,表示 JPEG 图像数据(仅几个前字符):

This is an example of the data sent from the client to my node, representing the JPEG image data (just a few first characters):

/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAFA3PEY8MlBGQUZaVVBfeM...

我通过以下操作在客户端获取此 数据 :

I'm getting this data on the client side by performing:

canvas.toDataURL('image/jpeg', 0.5).replace('data:image/jpeg;base64,', '')

这是我的 node.js 服务器中的函数用法:

Here is the function usage in my node.js server:

fs.writeFile('../some.jpeg', data, 'binary', function(err){});

不是将文件写入二进制文件(״״ JFIF ...),而是准确写入从客户端接收到的数据.

Instead of the file being written as binary (״״ JFIF ...), it writes exactly the data it received from the client.

我在这里做错了什么?

推荐答案

JavaScript 语言没有读取或操作二进制数据流的机制.Buffer 类是作为 Node.js API 的一部分引入的,以便在 TCP 流和文件系统操作等上下文中与八位字节流进行交互.

JavaScript language had no mechanism for reading or manipulating streams of binary data. The Buffer class was introduced as part of the Node.js API to make it possible to interact with octet streams in the context of things like TCP streams and file system operations.

纯 JavaScript 虽然非常适合 Unicode 编码的字符串,但不能很好地处理直接的二进制数据.

Pure JavaScript, while great with Unicode encoded strings, does not handle straight binary data very well.

当向套接字写入大量数据时,以二进制格式保存数据比从 Unicode 转换要高效得多.

When writing large amounts of data to a socket it's much more efficient to have that data in binary format vs having to convert from Unicode.

var fs = require('fs');
// string generated by canvas.toDataURL()
var img = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABQAAAAUCAYAAACNiR0"
    + "NAAAAKElEQVQ4jWNgYGD4Twzu6FhFFGYYNXDUwGFpIAk2E4dHDRw1cDgaCAASFOffhEIO"
    + "3gAAAABJRU5ErkJggg==";
// strip off the data: url prefix to get just the base64-encoded bytes
var data = img.replace(/^data:image/w+;base64,/, "");
var buf = Buffer.from(data, 'base64');
fs.writeFile('image.png', buf, /* callback will go here */);

参考

这篇关于使用node.js fs.writeFile写入二进制数据来创建镜像文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆