如何同步在Node.js中模拟unix head命令?

时间:2016-12-08 16:20:17

标签: node.js unix-head

在Node.js中寻找类似于linux head的同步方法。

我知道在节点中做同步事情通常是个坏主意,但我有一个有效的用例。需要阅读文件的前几行。

1 个答案:

答案 0 :(得分: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');
}