【问题标题】:Reading file using Node.js "Invalid Encoding" Error使用 Node.js 读取文件“无效编码”错误
【发布时间】:2020-06-06 07:41:43
【问题描述】:

我正在使用 Node.js 创建一个应用程序,并尝试读取一个名为“datalog.txt”的文件。我使用“追加”功能写入文件:

//Appends buffer data to a given file
function append(filename, buffer) {
  let fd = fs.openSync(filename, 'a+');

  fs.writeSync(fd, str2ab(buffer));

  fs.closeSync(fd);
}

//Converts string to buffer
function str2ab(str) {
  var buf = new ArrayBuffer(str.length*2); // 2 bytes for each char
  var bufView = new Uint16Array(buf);
  for (var i=0, strLen=str.length; i < strLen; i++) {
    bufView[i] = str.charCodeAt(i);
  }
  return buf;
}

append("datalog.txt","12345");

这似乎工作得很好。但是,现在我想使用fs.readFileSync 从文件中读取。我试过用这个:

const data = fs.readFileSync('datalog.txt', 'utf16le');

我把编码参数改成了the Node documentation中列出的所有编码类型,但都导致了这个错误:

TypeError: Argument at index 2 is invalid: Invalid encoding 

我想做的就是能够从“datalog.txt”中读取数据。任何帮助将不胜感激!

注意:一旦我可以读取文件的数据,我希望能够获得文件所有行的列表。

【问题讨论】:

  • fs.readFileSync('datalog.txt', 'utf-16') 工作吗?
  • richytong 没有同样的错误,对不起。

标签: node.js fs


【解决方案1】:

好的,经过几个小时的故障排除和查看文档后,我找到了解决方法。

try {
    // get metadata on the file (we need the file size)
    let fileData = fs.statSync("datalog.txt");
    // create ArrayBuffer to hold the file contents
    let dataBuffer = new ArrayBuffer(fileData["size"]);
    // read the contents of the file into the ArrayBuffer
    fs.readSync(fs.openSync("datalog.txt", 'r'), dataBuffer, 0, fileData["size"], 0);
    // convert the ArrayBuffer into a string
    let data = String.fromCharCode.apply(null, new Uint16Array(dataBuffer));
    // split the contents into lines
    let dataLines = data.split(/\r?\n/);
    // print out each line
    dataLines.forEach((line) => {
        console.log(line);
    });
} catch (err) {
    console.error(err);
}

希望它能帮助遇到同样问题的其他人!

【讨论】:

    【解决方案2】:

    编码和类型是一个对象:

    const data = fs.readFileSync('datalog.txt',  {encoding:'utf16le'});
    

    【讨论】:

    • 这不起作用并导致相同的错误。网上看了一下,好像只传字符串和传对象都是允许的。
    猜你喜欢
    • 1970-01-01
    • 2014-08-29
    • 2010-09-30
    • 1970-01-01
    • 2012-11-14
    • 2013-07-05
    • 1970-01-01
    • 2014-06-12
    • 2017-05-28
    相关资源
    最近更新 更多