Hi,
So I have just been asking chat GPT to create some code that will check for the existence of a folder, if if a folder doesn’t exist it will make one, and finally it will write a file to that destination.
It is quite an interesting process as you try to guide chat gpt, ‘can we break that down into separate functions?’, ‘how about using fs.access instead of fs.stat?’ etc
This is what it came up with.
const fs = require('fs').promises;
const path = require('path');
const ensureDirectoryExists = async (directoryPath) => {
try {
await fs.access(directoryPath);
} catch (err) {
if (err.code === 'ENOENT') {
await fs.mkdir(directoryPath, { recursive: true });
} else {
throw err;
}
}
};
const writeFile = async (filePath, data) => {
try {
await fs.writeFile(filePath, data);
console.log('File saved successfully.');
} catch (err) {
console.log('Error saving file: ', err);
}
};
const saveTest = async () => {
const filePath = 'public/non-existant-folder/some.txt';
const directoryPath = path.dirname(filePath);
try {
await ensureDirectoryExists(directoryPath);
await writeFile(filePath, 'Hello there!');
} catch (err) {
console.log('Error: ', err);
}
};
That looks pretty good to me, but this line from the nodejs docs throws a spanner in the works.
https://nodejs.org/api/fs.html#fspromisesaccesspath-mode
Using
fsPromises.access()
to check for the accessibility of a file before callingfsPromises.open()
is not recommended. Doing so introduces a race condition, since other processes may change the file’s state between the two calls. Instead, user code should open/read/write the file directly and handle the error raised if the file is not accessible.
I mentioned this to chat GPT and it came up with an alternative.
const fs = require('fs').promises;
const path = require('path');
const writeFile = async (filePath, data) => {
try {
const fileHandle = await fs.open(filePath, 'w');
await fileHandle.writeFile(data);
console.log('File saved successfully.');
await fileHandle.close();
} catch (err) {
console.log('Error saving file: ', err);
}
};
const saveTest = async () => {
const filePath = 'public/non-existant-folder/some.txt';
const directoryPath = path.dirname(filePath);
try {
await fs.mkdir(directoryPath, { recursive: true });
await writeFile(filePath, 'Hello there!');
} catch (err) {
console.log('Error: ', err);
}
};
I’m starting to feel like I am going down the rabbit hole with this now. I can’t find any up to date documentation or tutorials that give a clear cut way of performing this task.
Any input would be greatly appreciated.