2014-05-18 13 views
7

Próbuję odczytać plik w częściach: pierwsze 100 bajtów, a następnie .. Próbuję odczytać pierwsze 100 bajtów pliku /npm:node.js/odczyt 100 pierwszych bajtów pliku

app.post('/random', function(req, res) { 
    var start = req.body.start; 
    var fileName = './npm'; 
    var contentLength = req.body.contentlength; 
    var file = randomAccessFile(fileName + 'read'); 
    console.log("Start is: " + start); 
    console.log("ContentLength is: " + contentLength); 
    fs.open(fileName, 'r', function(status, fd) { 
     if (status) { 
      console.log(status.message); 
      return; 
     } 
     var buffer = new Buffer(contentLength); 
     fs.read(fd, buffer, start, contentLength, 0, function(err, num) { 
      console.log(buffer.toString('utf-8', 0, num)); 
     }); 
    }); 

wyjście jest:

Start is: 0 
ContentLength is: 100 

i następny błąd:

fs.js:457 
    binding.read(fd, buffer, offset, length, position, wrapper); 
     ^
Error: Length extends beyond buffer 
    at Object.fs.read (fs.js:457:11) 
    at C:\NodeInst\node\FileSys.js:132:12 
    at Object.oncomplete (fs.js:107:15) 

Co może być REAS na?

Odpowiedz

11

Dezorientujesz argument przesunięcia i położenia. Od the docs:

offset is the offset in the buffer to start writing at.

position is an integer specifying where to begin reading from in the file. If position is null, data will be read from the current file position.

powinien zmienić swój kod do tego:

fs.read(fd, buffer, 0, contentLength, start, function(err, num) { 
     console.log(buffer.toString('utf-8', 0, num)); 
    }); 

Zasadniczo offset to będzie indeks że fs.read zapisze do bufora. Powiedzmy, że masz bufor o długości 10 takich jak: <Buffer 01 02 03 04 05 06 07 08 09 0a>, a będziesz czytać z /dev/zero, który jest w zasadzie tylko zerami, i ustawić przesunięcie na 3 i ustawić długość na 4, a otrzymasz to: <Buffer 01 02 03 00 00 00 00 08 09 0a>.

fs.open('/dev/zero', 'r', function(status, fd) { 
    if (status) { 
     console.log(status.message); 
     return; 
    } 
    var buffer = new Buffer([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); 
    fs.read(fd, buffer, 3, 4, 0, function(err, num) { 
     console.log(buffer); 
    }); 
}); 

również dokonać rzeczy może chcesz spróbować użyć fs.createStream:

app.post('/random', function(req, res) { 
    var start = req.body.start; 
    var fileName = './npm'; 
    var contentLength = req.body.contentlength; 
    fs.createReadStream(fileName, { start : start, end: contentLength - 1 }) 
     .pipe(res); 
}); 
Powiązane problemy