Search code examples
node.jsfs

Reading file using Node.js "Invalid Encoding" Error


I am creating an application with Node.js and I am trying to read a file called "datalog.txt." I use the "append" function to write to the file:

//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");

This seems to work great. However, now I want to use fs.readFileSync to read from the file. I tried using this:

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

I changed the encoding parameter to all of the encoding types listed in the Node documentation, but all of them resulted in this error:

TypeError: Argument at index 2 is invalid: Invalid encoding 

All I want to be able to do is be able to read the data from "datalog.txt." Any help would be greatly appreciated!

NOTE: Once I can read the data of the file, I want to be able to get a list of all the lines of the file.


Solution

  • Okay, after a few hours of troubleshooting a looking at the docs I figured out a way to do this.

    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);
    }
    

    Hope it helps someone else with the same problem!