JavaScript fs.readFileSync返回什么编码? [英] What encoding does Javascript fs.readFileSync return?

查看:100
本文介绍了JavaScript fs.readFileSync返回什么编码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下Node.js Javascript程序:

Consider the following Node.js Javascript program:

var fs = require('fs');
var encoding1='?';
var encoding2='?';
var a = fs.readFileSync('./testdoc.pdf');
var b = new Buffer(fs.readFileSync('./testdoc.pdf',encoding1),encoding2);
console.log(a===b);

encoding1 encoding2 变量必须设置为什么值,以便在控制台上显示 true ?

To what values must the encoding1 and encoding2 variables be set in order for true to be printed at the console?

推荐答案

您需要 a.equals(b)

对于PDF之类的二进制数据,您应该使用"binary" 编码,但是没有一种编码会使任何两个缓冲区与 === 运算符相等,因此 a=== b 将始终为您提供 false .您需要使用 a.equals(b)来测试两个缓冲区的内容是否相同.

You need a.equals(b)

For binary data like PDF you should use the "binary" encoding but no encoding will make any two buffers equal with the === operator so a === b will always give you false. You need to use a.equals(b) to test if two buffers have the same contents.

请参阅文档中的 buf.equals(otherBuffer):

查看此代码:

var fs = require('fs');
var encoding1 = 'binary';
var encoding2 = 'binary';
var a = fs.readFileSync('./testdoc.pdf');
var b = new Buffer(fs.readFileSync('./testdoc.pdf', encoding1), encoding2);
console.log('Object equality:', a === b);
console.log('Buffer equality:', a.equals(b));

它将打印:

Object equality: false
Buffer equality: true

这篇关于JavaScript fs.readFileSync返回什么编码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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