Why does Sharp output the same file, even though I have changed the input file?
Asked Answered
H

1

7

After scaling and coloring a JPG with Sharp, I immediately delete the input file. When I upload a new file with the same name, Sharp will output the old file. I'm running NodeJS on Ubuntu 16.04.

Here is the code for editing the file:

sampleFile.mv(__dirname + "/" + name + "." + ext, function(err) {
    if (err)
      return res.status(500).send(err);

    res.send('File uploaded!');

    if (ext != "xlsx") {
      // This will attempt to resize the images
      console.log("Sharpening image")
      sharp(__dirname + "/" + name + "." + ext).resize({ height: 27 }).flatten( { background: '#ffffff' } ).toFile("/var/www/my_ip/file.jpg")
        .then(function(newFileInfo) {
          // newFileInfo holds the output file properties
          console.log("Success")
          try {
            fileSystem.unlinkSync(__dirname + "/" + name + "." + ext)
            //file removed
          } catch(err) {
            console.error(err)
          }
          })
        .catch(function(err) {
          console.log("Error occured with file " + name + "." + ext + " | Dir: " + __dirname);
          console.log(err)
          try {
          fileSystem.unlinkSync(__dirname + "/" + name + "." + ext)
            //file removed
          } catch(err) {
            console.error(err)
          }
          //})
        }); //this line errored
    }

  });

The first time I run it, it works just like intended, however if the file I use for the second run has the same name as the original file, it will somehow remember the old file and output that instead. I'm not sure how it remembers that file, as I immediately delete it. Any ideas on how to fix this?

Edit: To make sure the problem was not related to the first file not being properly deleted, I did a quick test. First, I use the server to edit 1 file, and I get that edited file as output, just as expected. Now, instead of editing a new file with the same name again, I restarted the server, then edited a new file with the same name. It now correctly outputted the new file. I believe the NPM must have some cache that I'm unaware of, currently reading the docs to so if my theory is correct.

Hoe answered 17/7, 2019 at 9:37 Comment(0)
H
12

Yes, my theory was correct! Sharp does have a cache, and for some reason keeps previously edited files open. It's probably good for optimization, but if you're having the same issues as me, and you're not worried about optimization, you can turn the cache of like so:

sharp.cache(false);
Hoe answered 17/7, 2019 at 10:21 Comment(1)
I've been losing one day trying to figure out why my input in the client was sending different file but in the server keep getting the same file over and over again ! And discovering that it was a problem on my node api server, and finally that it's sharp which cache it by default !Laoighis

© 2022 - 2024 — McMap. All rights reserved.