|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const{ Buffer }=require('buffer'); |
| 4 | +const{ FSReqWrap, close, read }=process.binding('fs'); |
| 5 | + |
| 6 | +constkReadFileBufferLength=8*1024; |
| 7 | + |
| 8 | +functionreadFileAfterRead(err,bytesRead){ |
| 9 | +constcontext=this.context; |
| 10 | + |
| 11 | +if(err) |
| 12 | +returncontext.close(err); |
| 13 | + |
| 14 | +if(bytesRead===0) |
| 15 | +returncontext.close(); |
| 16 | + |
| 17 | +context.pos+=bytesRead; |
| 18 | + |
| 19 | +if(context.size!==0){ |
| 20 | +if(context.pos===context.size) |
| 21 | +context.close(); |
| 22 | +else |
| 23 | +context.read(); |
| 24 | +}else{ |
| 25 | +// unknown size, just read until we don't get bytes. |
| 26 | +context.buffers.push(context.buffer.slice(0,bytesRead)); |
| 27 | +context.read(); |
| 28 | +} |
| 29 | +} |
| 30 | + |
| 31 | +functionreadFileAfterClose(err){ |
| 32 | +constcontext=this.context; |
| 33 | +constcallback=context.callback; |
| 34 | +letbuffer=null; |
| 35 | + |
| 36 | +if(context.err||err) |
| 37 | +returncallback(context.err||err); |
| 38 | + |
| 39 | +try{ |
| 40 | +if(context.size===0) |
| 41 | +buffer=Buffer.concat(context.buffers,context.pos); |
| 42 | +elseif(context.pos<context.size) |
| 43 | +buffer=context.buffer.slice(0,context.pos); |
| 44 | +else |
| 45 | +buffer=context.buffer; |
| 46 | + |
| 47 | +if(context.encoding) |
| 48 | +buffer=buffer.toString(context.encoding); |
| 49 | +}catch(err){ |
| 50 | +returncallback(err); |
| 51 | +} |
| 52 | + |
| 53 | +callback(null,buffer); |
| 54 | +} |
| 55 | + |
| 56 | +classReadFileContext{ |
| 57 | +constructor(callback,encoding){ |
| 58 | +this.fd=undefined; |
| 59 | +this.isUserFd=undefined; |
| 60 | +this.size=undefined; |
| 61 | +this.callback=callback; |
| 62 | +this.buffers=null; |
| 63 | +this.buffer=null; |
| 64 | +this.pos=0; |
| 65 | +this.encoding=encoding; |
| 66 | +this.err=null; |
| 67 | +} |
| 68 | + |
| 69 | +read(){ |
| 70 | +letbuffer; |
| 71 | +letoffset; |
| 72 | +letlength; |
| 73 | + |
| 74 | +if(this.size===0){ |
| 75 | +buffer=this.buffer=Buffer.allocUnsafeSlow(kReadFileBufferLength); |
| 76 | +offset=0; |
| 77 | +length=kReadFileBufferLength; |
| 78 | +}else{ |
| 79 | +buffer=this.buffer; |
| 80 | +offset=this.pos; |
| 81 | +length=Math.min(kReadFileBufferLength,this.size-this.pos); |
| 82 | +} |
| 83 | + |
| 84 | +constreq=newFSReqWrap(); |
| 85 | +req.oncomplete=readFileAfterRead; |
| 86 | +req.context=this; |
| 87 | + |
| 88 | +read(this.fd,buffer,offset,length,-1,req); |
| 89 | +} |
| 90 | + |
| 91 | +close(err){ |
| 92 | +constreq=newFSReqWrap(); |
| 93 | +req.oncomplete=readFileAfterClose; |
| 94 | +req.context=this; |
| 95 | +this.err=err; |
| 96 | + |
| 97 | +if(this.isUserFd){ |
| 98 | +process.nextTick(functiontick(){ |
| 99 | +req.oncomplete(null); |
| 100 | +}); |
| 101 | +return; |
| 102 | +} |
| 103 | + |
| 104 | +close(this.fd,req); |
| 105 | +} |
| 106 | +} |
| 107 | + |
| 108 | +module.exports=ReadFileContext; |
0 commit comments