2014-05-18 15 views
7

Sto provando a leggere un file in parti: i primi 100 byte e poi su .. Sto provando a leggere i primi 100 byte del file /npm:node.js/leggi 100 primi byte di un file

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)); 
     }); 
    }); 

l'output è:

Start is: 0 
ContentLength is: 100 

e il successivo errore:

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) 

Quali possono essere le Reas sopra?

risposta

11

Stai confondendo l'argomento di spostamento e posizione. Da 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.

Si dovrebbe cambiare il codice per questo:

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

Fondamentalmente la offset è sarà indice che fs.read scriverà al buffer. Diciamo che hai un buffer con lunghezza pari a 10 come questo: <Buffer 01 02 03 04 05 06 07 08 09 0a> e leggerai dal /dev/zero che è fondamentalmente solo zeri, e imposta l'offset su 3 e imposta la lunghezza su 4 quindi otterrai questo: <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); 
    }); 
}); 

anche a fare cose che si potrebbe desiderare di provare a utilizzare 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); 
}); 
Problemi correlati