Unexpected Node.js Behavior when using fsPromises.open

66 views Asked by At

I have a larger app that is erroring out during this file writing operation. I'm trying to use fsPromises to create an autosave file, but the path variable I'm passing in appears to be losing it's value in between a debugging console log and the actual call to open the file. It's very odd.

here's the code:

    static async writeFile(filepath, data) {
        try {
            console.log(4, filepath, typeof filepath);
            console.log(5, path.resolve(filepath))
            const fileHandle = await fs.open(filepath, 'w+');
            console.log(6, fileHandle)
            await fileHandle.truncate();
            await fileHandle.writeFile(data, 'utf8');
            await fileHandle.close();
        } catch (error) {
            throw new Error(`Error writing file: ${error.message}`);
        }
    }

here's the relevant output (I've removed the directory structure, but I check it 5 times each time I run the script, and the output is optimized to find differences in strings easily, so I'm 99.99% sure the directory of the file location is correct)

4 C:\__dirname\savefile-autosave-2023-10-21T00:06:11.306Z.json string
5 C:\__dirname\savefile-autosave-2023-10-21T00:06:11.306Z.json
Error saving auto-save file: Error saving save file: Error writing file: ENOENT: no such file or directory, open 'C:\__dirname\savefile-autosave-2023-10-21T00:06:11.306Z.json'
Error: The "path" argument must be of type string or an instance of Buffer or URL. Received undefined

to my knowledge, calling fsPromises (lazily called fs here, but it's defined as const fs = require('fs').promises at the top of the file) with the w+ flag should open the file even if it doesn't exist. But the error appears to be with something before that flag becomes relevant. I don't understand how console logs 4 and 5 are reading out the correct information, but the open function appears is some how getting undefined, even though the console logs are showing the variable as being defined. I'm not even sure what more I can do to debug this at this point. Any help will be greatly appreciated!

I forgot some important information: I'm on windows using node version 18.18.2

1

There are 1 answers

0
bearaxe On BEST ANSWER

As pointed out by @JaromandaX's comment, the : character in the ISOString result is causing the issue because it's an invalid character in the Windows directory naming style