首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在Node.js中同步模拟unix head命令?

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

Stack Overflow用户
提问于 2016-12-09 00:20:17
回答 1查看 412关注 0票数 0

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

我知道在node中进行同步操作通常不是一个好主意,但我有一个有效的用例。需要读取文件的前几行。

EN

回答 1

Stack Overflow用户

发布于 2016-12-09 00:20:17

代码语言:javascript
运行
复制
// 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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41044091

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档