简体   繁体   中英

Javascript / NodeJs - fs.readFile using callback before file is read

I'm using Node/JavaScript to read an image file from disk, and pass that file via socket encoded as base64. The code is solid (although I'm sure some of you will offer better ways of coding :) ), however the issue I'm encountering seems to be related to the callback implementing before the file has been full read (sometimes).

I can trap the error by looking for a typeof === 'undefined' but I'm not 100% what I can do once this has thrown

watcher.on('create', function callBack(file){
    return readFile(file);
});

function readFile(file){
    console.log(file);
    fs.readFile(file, function(err, data){
        if(err){ 
            console.log(err);
            throw err};

                io.emit('image', {image: true, buffer: data.toString('base64') });

    });

}

The error received is

{ [Error: EBUSY: resource busy or locked, open 'filename']
  errno: -4082,
  code: 'EBUSY',
  syscall: 'open',
  path: 'filename' }

Is there anyway to wait/pause the async operation until the file has been fully read?

You you read the manual more carefully you will see the callback calls only when your file is read. In your can the error says 'your file already is busy'.

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