我想知道用Node.js检查文件是二进制还是ASCII的最佳方法是什么?
似乎有两种不特定于node.js的方法:
检查MIME类型:How to Check if File is ASCII or Binary in PHP - 但是这有问题,例如前驱前辈通常没有识别的mime类型,并在使用时检查它们时恢复为application/octet-stream
mime
通过使用How to identify the file content as ASCII or binary的流缓冲区检查字节大小 - 这似乎非常密集,并且还提供了node.js示例。
那么还有另一种方式吗?也许是一个我不知道的秘密node.js呼叫或模块?或者如果我必须自己这样做,会建议采用什么方式?
由于
答案 0 :(得分:11)
感谢David Schwartz对此问题的评论,我创建了istextorbinary来解决此问题。
答案 1 :(得分:4)
ASCII defines characters 0-127,因此如果文件的整个内容是该范围内的字节值,则可以将其视为ASCII文件。
function fileIsAscii(filename, callback) {
// Read the file with no encoding for raw buffer access.
require('fs').readFile(filename, function(err, buf) {
if (err) throw err;
var isAscii = true;
for (var i=0, len=buf.length; i<len; i++) {
if (buf[i] > 127) { isAscii=false; break; }
}
callback(isAscii); // true iff all octets are in [0, 127].
});
}
fileIsAscii('/usr/share/dict/words', function(x){/* x === true */});
fileIsAscii('/bin/ls', function(x){/* x === false */});
如果性能至关重要,那么请考虑根据链接的答案编写自定义C ++函数。
答案 2 :(得分:1)
我是从谷歌来的,但由于找不到满意的答案,我采取了另一种适合我的方法:
const string_to_test = "I am just a piece of text";
//const binary_to_test = "��˰!1�H��1�1����!H�=u�!�";
if(/\ufffd/.test(string_to_test) === true){
console.log("I'm 'binary'");
}else{
console.log("I'm proper text");
}
它是如何运作的?如果您尝试以正常方式打开二进制数据(不使用十六进制编辑器),它将遇到一些渲染问题,这些问题会转换为您作为这个奇怪字符的继承 称为“替换字符”。