简体   繁体   中英

Close stream node.js

I am not able to close a stream in node.js this is my code

        var inp = fs.createReadStream("a/b/c/"+ Name);
        var out = fs.createWriteStream("a/b/c/"+ Name);
        inp.pipe(out);
            inp.close( function(err){
              if (err){
                console.log(err);
              } else {
              inp.unpipe(out);
              socket.emit('Done',{'Name':name});
              console.log('There will be no more data.');
              }
            });

Then i have this function further down in my code that deletes the directory the directory of inp

var fse = require("fs-extra");
fse.emptyDir("a/b/c/", function(err){
  if(err){
    console.log(err);
  } else {
    console.log("doneaaaa")
    fse.remove("a/b/c",function(err){
      if(err){
        console.log(err);
      } else {
        console.log('doneaswell');
      }
    });
  }
});

and i get this error !!

doneaaaa
{ [Error: EBUSY: resource busy or locked, unlink 'a/b/c/.nfs000000002ab5000d00000072']
  errno: -16,
  code: 'EBUSY',
  syscall: 'unlink',
  path: 'a/b/c/.nfs000000002ab5000d00000072' }

Which means the stream is still open !

.nfs file is created while streaming right , but shouldn't file delete once the stream is closed ?

What am I doing wrong ?

You have to wait for the callback to close to be invoked before you do a remove/unlock operation. From the samples you provided it doesn't look like this is the case.

Node.js runs async, which means that the deletion of the directory occours during the stream. Instead try putting the deletion inside of the callback so it occours after:

var inp = fs.createReadStream("a/b/c/"+ Name);
var out = fs.createWriteStream("a/b/c/"+ Name);
inp.pipe(out);
inp.close( function(err){
  if (err){
    console.log(err);
  } else {
    inp.unpipe(out);
    socket.emit('Done',{'Name':name});
    console.log('There will be no more data.');
  }

  var fse = require("fs-extra");
  fse.emptyDir("a/b/c/", function(err){
    if(err){
      console.log(err);
    } else {
      console.log("doneaaaa");
      fse.remove("a/b/c",function(err){
        if(err){
          console.log(err);
        } else {
          console.log('doneaswell');
        }
      });
    }
  });
});

You were also missing a semicolon on one line which I added in this code as well :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM