S
S
sorokinfil2018-03-14 00:19:53
Node.js
sorokinfil, 2018-03-14 00:19:53

How to overcome obscure fs.unlink error in node.js?

There is a table in MySQL, which has links to pictures (originals and previews). On the node, I get all these pictures, bypass them in a loop and delete everything. If there is more than one pair of images (the pair is original and preview), the node generates an error:
Error: EPERM: operation not permitted, unlink 'C:\path_to_image\aa\bb\12345.jpg
' the rest (34772.jpg, 87202.jpg, ...) are not deleted, although they should. The solution is completely non-obvious for me, I did not find anything sensible on the Internet, except for downgrading npm to version 5.3.0, which did not help me.
Windows 7, command line run as administrator
Node.js 8.9.4
npm 5.3.0
Loop code:

for (var i=0; i<result.length; i++)
        {
          if (result[i].img)
          {
            var path_image = path.resolve (CONFIG.STORAGE_DIR_PORTFOLIO, result[i].img);
            fs.open (path_image, 'r', (err, fd) =>
            {
              if (err)
              {
                /* Если файл не найден, то ничего не делаем */
                if (err.code === 'ENOENT')
                  return;
                throw err;
              }
              
              /* Удаляем картинку */
              fs.unlink (path_image, function (err)
              {
                if (err)
                  throw err;
              });
            });
          }
          if (result[i].image_preview)
          {
            var path_image_preview = path.resolve (CONFIG.STORAGE_DIR_PORTFOLIO, result[i].image_preview);
            fs.open (path_image_preview, 'r', (err, fd) =>
            {
              if (err)
              {
                /* Если файл не найден, то ничего не делаем */
                if (err.code === 'ENOENT')
                  return;
                throw err;
              }
              
              /* Удаляем превью */
              fs.unlink (path_image_preview, function (err)
              {
                if (err)
                  throw err;
              });
            });
          }
        }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
RidgeA, 2018-03-14
@RidgeA

There is a suspicion that the problem is that fs.open opens a file descriptor, therefore, most likely, the file is not deleted correctly.

V
Vladimir Skibin, 2018-03-14
@megafax

Don't be afraid to use synchronous functions

result.forEach((item) => {
  return ((images) => {
    images.forEach((image) => {
      if (image) {
        let pathImg = path.resolve(CONFIG.STORAGE_DIR_PORTFOLIO, image);
        return fs.existsSync(pathImg) && fs.unlinkSync(pathImg);
      }
    })
  })([item.img, item.image_preview]);
});

Or do you still need the result of the removal?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question