How to replace existing file on a server
Hi, there! Thank you for your time and effort you put in this library. I have a question about replacing existing files stored on a server.
I use your library to save users profile pictures. So I save them by user id. And I want to replace existing file with new one on PATCH request.
I have read this section but there is no function to check if there is an existing file with provided name. I thought that storeFileLocally will replace file if I provide same name but it just throws an error:
[nuxt] [request error] [unhandled] [500] EEXIST: file already exists, mkdir './files/profile'
my code:
const name = await storeFileLocally(body.image, `${event.context.user.id}`, '/profile');
Is there a way to check for existence of same name file? Or just replacing if there is one? Or maybe you will add this functionality soon?
Hey Elijjahh, I will look into fixing this issue, in the meantime you could use getFileLocally to check if the file exists, deleteFile to delete it if it exists and then storing a new file.
something similar to this (UNTESTED CODE):
// ! assuming the profile image is in a specific format like png
const fileExists = await getFileLocally(`${event.context.user.id}.png`, '/profile')
if (fileExists) {
await deleteFile(`${event.context.user.id}.png`, '/profile')
}
const name = await storeFileLocally(
body.image,
event.context.user.id,
'/profile'
)
Thank you for reporting this issue and I apologize for the inconvenience.
Actually, I tried to delete file but error didn't go away. So I tried to google this error and after reading this article I tried to look at your code. Now it seems that you dont handle mkdir error for already existing folder.
I tried to wrap mkdir with try catch and now error is gone.
export const storeFileLocally = async (
file: ServerFile,
fileNameOrIdLength: string | number,
filelocation: string = '',
) => {
const { binaryString, ext } = parseDataUrl(file.content);
const location = useRuntimeConfig().public.fileStorage.mount;
const originalExt = file.name.toString().split('.').pop() || ext;
const filename =
typeof fileNameOrIdLength == 'number'
? `${generateRandomId(fileNameOrIdLength)}.${originalExt}`
: `${fileNameOrIdLength}.${originalExt}`;
// I changed this part
try {
await mkdir(join(location, filelocation), { recursive: true });
} catch (error) {
console.log(error);
}
await writeFile(join(location, filelocation, filename), binaryString, {
flag: 'w',
});
return filename;
};