使用javascript读取二进制文件并转换为字符

时间:2015-01-16 05:47:02

标签: javascript node.js

我试图读取二进制文件并尝试将其转换为字符
这是代码
我不确定这是一种正确的方式 专家请纠正我

var fs = require('fs');   
fs.readFile('C:/parsing/test.prn',  function (err, data) {
    bufferString = data.toString();     
    bufferStringSplit = bufferString.split('\n');  
    var byteArray = getBytes(bufferStringSplit[50]); // converting to byte array
    console.log(byteArray.length)


    var result1 = "";
    for (var i = 0; i < byteArray.length; i++) {
        console.log(byteArray[i],"-----------------byte array")
        result1 += String.fromCharCode(parseInt(byteArray[i], 2)); // converting to charecter
    }
});

function getBytes(str) {
    var bytes = [], char;
    str = encodeURI(str);

    while (str.length) {
        char = str.slice(0, 1);
        str = str.slice(1);

        if ('%' !== char) {
            bytes.push(char.charCodeAt(0));
        } else {
            char = str.slice(0, 2);
            str = str.slice(2);

            bytes.push(parseInt(char, 16));
        }        }

    return bytes;
};

我使用的另一个代码

var fs = require('fs');

fs.open('C:/parsing/test.prn', 'r', function(err, fd) {
var result ="";
  if (err)
    throw err;
  var buffer = new Buffer(100);
  while (true)
  {   
    var num = fs.readSync(fd, buffer, 0, 1, null);
    if (num === 0)
      break;
    console.log('byte read', buffer[0]);
    result += String.fromCharCode(parseInt(buffer[0], 2));
  }
  console.log(result)
});

console.log(result)打印如下

  

♥☺☺☺☺☺☺☺☺☺☺☺☺☺☺♥☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☺☻☻☺☻☻☻☺☻☺☺☺ ☺☺☺☺☺☺☺☺☺☺♥♥♥♥♥♥♥♥♥♥♥♥♥♥♥

0 个答案:

没有答案