Zander
Zander

Reputation: 1086

Sharp keeps image processing after creating a thumbnail

I have server.js where, when uploading an image, Sharp creates a thumbnail.

The main issue is that if later I want to delete the main image, it won't let me because something is using it.

File not accessible: C:\Users\...\uploads\Fan-Art\test-1738586514023.jpg Error: EPERM: operation not permitted, unlink 'C:\Users\...\furwork\uploads\Fan-Art\test-1738586514023.jpg'

Even if I try to delete the image manually, it tells me that something is using it and prevents to delete it. But if I stop the server.js I can delete it without any problem.

I tried not to create a thumbnail, and I could delete the image accordingly without any problem, deleting it from the website and manually.

This is my endpoint on the server.js

app.post('/upload-submission', upload.any(), async (req, res) => {
    const folderPath = req.body.folderPath;
    const targetDir = path.join(__dirname, folderPath);
    console.log('Resolved path:', targetDir);
    ...
        // Generate the thumbnail and ensure it finishes before proceeding
        const thumbnailName = `thumb-${path.basename(mainFile.path)}`;
        const thumbnailPath = path.join(targetDir, thumbnailName);

        try {
            // This ensures the Sharp process finishes before continuing
            await sharp(path.join(targetDir, path.basename(mainFile.path)))
                .resize(150, 150)
                .toFile(thumbnailPath);
            console.log("Thumbnail created successfully.");
        } catch (err) {
            console.error('Error creating thumbnail:', err);
            throw new Error('Error creating thumbnail');
        }
        ...
    } catch (err) {
        ...
    }
});

Versions using:

"express": "^4.21.1",
"axios": "^1.7.8",
"sharp": "^0.33.5",
"multer": "^1.4.5-lts.1",

Upvotes: 1

Views: 53

Answers (1)

Zander
Zander

Reputation: 1086

It seems that Sharp can have troubles on Windows leaving the main image open.

What I can use, and worked perfectly fine, is create a new buffer from the original image, and use it to create the thumbnail.

// Get the path to the main image
const mainImagePath = path.join(targetDir, path.basename(mainFile.path));
// Read the image into a buffer
const imageBuffer = await fs.promises.readFile(mainImagePath);

// Use the buffer as Sharp’s input
await sharp(imageBuffer)
    .resize(150, 150)
    .toFile(thumbnailPath);
console.log("Thumbnail created successfully.");

Upvotes: 0

Related Questions