-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.js
More file actions
82 lines (62 loc) · 2.09 KB
/
test.js
File metadata and controls
82 lines (62 loc) · 2.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
const fs = require("mz/fs");
// Some parts of code i borrowed
function readLinesFromFile(path, maxLineCount) {
const NEW_LINE_CHARACTERS = ["\n"];
const readPreviousChar = function( stat, file, currentCharacterCount) {
return fs.read(file, Buffer.alloc(1), 0, 1, stat.size - 1 - currentCharacterCount)
.then((bytesReadAndBuffer) => {
return String.fromCharCode(bytesReadAndBuffer[1][0]);
});
};
return new Promise((resolve, reject) => {
let self = {
stat: null,
file: null,
};
fs.exists(path).then(() => {
let promises = [];
promises.push(
fs.stat(path)
.then(stat => self.stat = stat));
promises.push(
fs.open(path, "r")
.then(file => self.file = file));
return Promise.all(promises);
}).then(() => {
let chars = 0;
let lineCount = 0;
let lines = "";
const do_while_loop = function() {
if (lines.length > self.stat.size) {
lines = lines.substring(lines.length - self.stat.size);
}
if (lines.length >= self.stat.size || lineCount >= maxLineCount) {
if (NEW_LINE_CHARACTERS.includes(lines.substring(0, 1))) {
lines = lines.substring(1);
}
fs.close(self.file);
return resolve(Buffer.from(lines, "binary").toString('utf-8'));
}
return readPreviousChar(self.stat, self.file, chars)
.then((nextCharacter) => {
lines = nextCharacter + lines;
if (NEW_LINE_CHARACTERS.includes(nextCharacter) && lines.length > 1) {
lineCount++;
}
chars++;
})
.then(do_while_loop);
};
return do_while_loop();
})
});
}
async function timeTest(){
let st = new Date().getTime();
const res = await readLinesFromFile('t.txt' , 50000)
console.log('get res')
let fn = new Date().getTime();
console.log(`ThirdWay: ${fn - st}ms`)
}
//readLinesFromFile('somefile.txt' , 5).then(res => console.log(res))
timeTest()