read-first-line
Version:
Read first line of the file. Works fine with LF and CRLF line endings.
29 lines (28 loc) • 874 B
JavaScript
;
const fs = require("fs");
function readFirstLine(filePath) {
return new Promise((resolve, reject) => {
const rs = fs.createReadStream(filePath, { encoding: "utf8" });
let acc = "";
let pos = 0;
let index;
rs.on("data", function (chunk) {
index = chunk.indexOf("\r\n");
if (index === -1) {
index = chunk.indexOf("\n");
}
acc += chunk;
index !== -1 ? rs.close() : (pos += chunk.length);
})
.on("close", function () {
if (index !== -1) {
return resolve(acc.slice(0, pos + index));
}
resolve(acc.slice(0, pos));
})
.on("error", function (err) {
reject(err);
});
});
}
module.exports = readFirstLine;