Using API to change local file names
Unanswered
Richard Evanson posted this in #help-forum
I am trying to make API to rename local files in public/game images folder but I have no lock.
this is my renameImage.js file
I import it to other client componenet
and I use it in part of other function like this
right now I am getting this error
Unhandled Runtime Error
Error: res.status is not a function
but I am still confused what most of it means
this is my renameImage.js file
'use server'
import fs from 'fs';
import path from 'path';
export default async function renameImage(req, res) {
console.log('Request object:', req);
console.log('Response object:', res);
if (req.method === 'POST') {
const { oldFileNameWithExtension, newFileNameWithExtension } = req.body;
try {
const oldFilePath = path.join(process.cwd(), 'public', 'Game Images', oldFileNameWithExtension);
const newFilePath = path.join(process.cwd(), 'public', 'Game Images', newFileNameWithExtension);
fs.renameSync(oldFilePath, newFilePath);
res.status(200).json({ success: true, message: 'File renamed successfully.' });
} catch (error) {
console.error(error);
res.status(500).json({ success: false, message: 'Internal server error.' });
}
} else {
res.status(405).json({ success: false, message: 'Method Not Allowed' });
}
}I import it to other client componenet
import renameImage from '@/app/api/renameImage';and I use it in part of other function like this
if (editItem.ImageName !== editedEntry.ImageName) {
const oldFileNameWithExtension = editItem.ImageName + '.png';
const newFileNameWithExtension = editedEntry.ImageName + '.png';
renameImage(oldFileNameWithExtension, newFileNameWithExtension);
}right now I am getting this error
Unhandled Runtime Error
Error: res.status is not a function
but I am still confused what most of it means
10 Replies
you can just return the object in your server action.
res.status or res.json is page router things
res.status or res.json is page router things
if (editItem.ImageName !== editedEntry.ImageName) {
const oldFileNameWithExtension = editItem.ImageName + '.png';
const newFileNameWithExtension = editedEntry.ImageName + '.png';
renameImage(oldFileNameWithExtension, newFileNameWithExtension);
}you are passing two string to the renameImage function so your server action is receiving
export default async function renameImage(oldFileNameWithExtension: string, newFileNameWithExtension: string) {}but do I even need res? this is all just for local files there is no database
I just want to give 2 file names and have it change it from first to second
there is no res in app router
you can just return a object from the server action
return { success: true, message: 'File renamed successfully.' };so then I just send 1 object of somehow connected both old and new file name?
this is all very confusing
just treat it as normal function but you can do server stuff in it