Reputation: 1342
Hi I'm trying to follow a tutorial on Electron however I keep getting this error when trying to open a file from the menu i've made.
Uncaught Exception: TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be one of type string, Buffer, or URL. Received type undefined...
Here is my function.
function openFile() {
// Opens file dialog looking for markdown
const files = dialog.showOpenDialog(mainWindow, {
properties: ['openFile'],
filters: [{ name: 'Markdown', extensions: ['md', 'markdown', 'txt'] }]
});
// If no files
if (!files) return;
const file = files[0]; // Grabs first file path in array
// Loads file contents via path acquired via the dialog
const fileContent = fs.readFileSync(file).toString();
console.log(fileContent);
}
Tried reverting back to older versions etc. To no avail.
Thanks for any advice.
Upvotes: 0
Views: 1052
Reputation: 722
Careful here, showOpenDialog()
is an async function and returns a promise.
In your case the correct usage is:
dialog.showOpenDialog(mainWindow, {
properties: ['openFile'],
filters: [{ name: 'Markdown', extensions: ['md', 'markdown', 'txt'] }]
}).then(result => {
const file = result.filePaths[0];
const fileContent = fs.readFileSync(file).toString();
console.log(fileContent);
}).catch(err => {
console.log(err)
});
Also consider using readFile
instead of readFileSync
to avoid blocking the Electron main thread.
Upvotes: 4