2016-12-08 3 views
0

Suche nach einer synchronen Methode in Node.js, die wie Linux-Kopf ist.Wie kann ich den Unix-Kopfbefehl in Node.js synchron simulieren?

Ich weiß, es ist generell eine schlechte Idee, synchrone Sachen in Knoten zu tun, aber ich habe einen gültigen Anwendungsfall. Müssen die ersten Zeilen einer Datei lesen.

+1

Ich möchte einen gültigen Anwendungsfall für synchrone E/A in node.js Server irgendwo anders als Start sehen. – jfriend00

Antwort

0
// Returns the first few lines of the file. 
// file: the file to read. 
// lines: the number of lines to return. 
// maxBuffer: the maximum number of bytes to read from 
//   the beginning of the file. We default to 
//   1k per line requested. 
function head(file, lines, maxBuffer) { 
    lines = lines || 10; 
    maxBuffer = maxBuffer || lines * 1000; 
    var stats = fs.statSync(file); 
    var upToMax = Math.min(maxBuffer, stats.size); 
    var fileDescriptor = fs.openSync(file, 'r'); 
    var buffer = Buffer.alloc(upToMax); 
    fs.readSync(fileDescriptor, buffer, 0, upToMax, 0); 
    var lineA = buffer.toString('utf8').split(/\r?\n/); 
    lineA = lineA.slice(0, Math.min(lines, lineA.length)); 
    // might be nicer just to return the array and let the 
    // caller do whatever with it. 
    return lineA.join('\n'); 
} 
+0

Sie können auch einfach https://www.npmjs.com/package/head verwenden –

Verwandte Themen