-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathshell.js
More file actions
85 lines (72 loc) · 2.31 KB
/
shell.js
File metadata and controls
85 lines (72 loc) · 2.31 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
83
84
85
var path = require('path');
var fs = require('fs');
var stdin = process.openStdin();
var commands = {
'ls': function (args) {
fs.readdir(args[0] || process.cwd(), function (err, entries) {
entries.forEach(function (e) {
console.log(e);
});
});
},
'pwd': function () {
console.log(process.cwd());
},
'cd': function (args) {
process.chdir(path.resolve(process.cwd(), args[0]));
},
'head': function () {
},
'tail': function (args) {
fs.stat(args[0], function (err, stats) {
if (stats.size === 0) {
return;
}
var options = {
flags: 'r',
encoding: 'utf8',
mode: 0666,
bufferSize: 10,
start: 0,
end: stats.size
};
var offset = 0;
// Keep track of one extra newline
// So we can start reading in the contents starting
// at the next character
var numLines = (args[1] || 10) + 1;
var newLines = new Array(numLines);
var index = 0;
var fileStream = fs.createReadStream(args[0], options);
fileStream.on('data', function (data) {
for (var i = 0; i < data.length; i++) {
if (data[i] === '\n') {
newLines[index] = offset + i;
index = ++index % numLines;
}
}
offset += data.length;
});
fileStream.on('end', function () {
if (typeof newLines[index] === 'number') {
var position = newLines[index] + 1;
}
else {
var position = 0;
}
var bytesToRead = stats.size - position;
fs.open(args[0], 'r', function (err, fd) {
var buffer = new Buffer(bytesToRead);
fs.readSync(fd, buffer, 0, bytesToRead, position);
console.log(buffer.toString())
});
});
});
}
};
stdin.on('data', function (d) {
var matches = d.toString().match(/(\w+)(.*)/i);
var command = matches[1].toLowerCase();
var args = matches[2].trim().split(/\s+/);
commands[command](args);
});