node-klaw icon indicating copy to clipboard operation
node-klaw copied to clipboard

fs.remove inside the walk leads to the errors

Open PavelPolyakov opened this issue 9 years ago • 3 comments

Hi,

Imagine that I want to walk through the directory contents and remove all the directories there.

Here is my directory:

tmp
├── dir1
│   └── hello.txt
├── dir2
├── dir3
└── hello.txt

3 directories, 2 files

Here is my code:

'use strict';

const klaw = require('klaw');
const through2 = require('through2');
const fs = require('fs-extra');


fs.walk('./tmp')
  .pipe(through2.obj((function (item, enc, next) {
  if (item.stats.isDirectory()) {
    fs.remove(item.path)
  }
  next();
})))
  /*.on('data', function (item) {

  })*/
  .on('end', function () {
    console.log('end of everything');
  })

Here is the error I have during the execution: image

After the execution the directory looks the next way:

tmp
└── dir1
    └── hello.txt

1 directory, 1 file

I have tried different variants, including the marking the items as removed, but I haven't yet found anything working.

Could you, please, clarify if it's possible to cleanup the directory while "klawling" through it?

Regards,

PavelPolyakov avatar May 19 '16 09:05 PavelPolyakov

The problem is that you're not calling the callback on fs.remove. Also, since you're using fs-extra, you don't need to include klaw since fs-exta already does. Your code can be simplified to:

var fs = require('fs-extra')

fs.walk('./tmp')
  .pipe(through2.obj((function (item, enc, next) {
  if (item.stats.isDirectory()) {
    fs.remove(item.path, next) // <--- next
  }
})))
  /*.on('data', function (item) {

  })*/
  .on('end', function () {
    console.log('end of everything');
  })

Hope this helps.

jprichardson avatar May 19 '16 13:05 jprichardson

@jprichardson Ah, clear, thanks.

Do I understand correctly, that it's only possible to do that inside the "pipe"? It's not possible to do that from the data event? Because there is no callback there.

Right?

PavelPolyakov avatar May 19 '16 13:05 PavelPolyakov

No, you can do it in the 'data' event....

.on('data', function (item) { 
  fs.remove(item.path)
})

But yea... it should still delete them. Hmm, there may be a bug here...

jprichardson avatar May 19 '16 13:05 jprichardson