Search code examples
node.jswindowsencodingelectronreadfile

fs.readFile can't read file paths on windows, wrong encoding?


I'm passing the string "C:\random-folder\ui-debug.log" file path to fs.readFile() on a virtualized Windows 11 installation under macos and a x64 bit electron installation and nodeJS 18 (idk if that matters).

Using the following code:

const filepath = path.resolve(path.normalize(pathStr))
const file = fs.readFileSync(filepath)

but continuously get this error:

TypeError [ERR_INVALID_ARG_VALUE]: The argument 'path' must be a string or Uint8Array without null bytes. Received 'C:\\random-folder\\ui-debug.log\x00'

The file path always seems to be interpreted incorrectly by readFileSync, the \x00 is always added to the end of the path it errors with. This same code works fine on macos.

What is the correct way to read arbitrary file paths with nodejs/electron under Windows? Thanks!


Solution

  • The issue was to do with how the string was being parsed in the first place. Before passing the filepath to readFileSync, it was being converted to ucs2

    const pathStr = clipboard.readBuffer('FileNameW').toString('ucs2')
    

    On windows some extra characters were added at the end of the string but was console logged as normal (some internal conversion going on?) so it looked like a normal path in console but internally it had some extra encoded characters on the end.

    I solved it with some regex:

    const pathStr = clipboard.readBuffer('FileNameW').toString('ucs2').replace(RegExp(String.fromCharCode(0), 'g'), '')
    

    Now readFileSync reads the file just fine!