简体   繁体   English

Javascript / NodeJs-fs.readFile在读取文件之前使用回调

[英]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. 我正在使用Node / JavaScript从磁盘读取图像文件,并通过编码为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 我可以通过查找typeof === 'undefined'来捕获错误,但是一旦抛出该错误,我就不能100%

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. 您仔细阅读了手册之后,只有在读取文件时才会看到callback调用。 In your can the error says 'your file already is busy'. 在您的罐子里,错误提示“您的文件已经很忙”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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