Tôi thấy rằng tiền thưởng sắp kết thúc ... tôi có thể có được không? Nếu tôi đã nói với bạn:
Chuyển đến Đoạn mã nếu bạn quen với tìm kiếm lịch sử và muốn sử dụng nó làm phương án thay thế.
Bạn có quen thuộc với tìm kiếm lịch sử của zsh không? Nó gần giống như tìm kiếm ngược lại, ngoại trừ thực tế là bạn có thể bắt đầu tìm kiếm sau khi nhập một cái gì đó trên dòng lệnh và nhấn phím mũi tên up
. Tôi tìm thấy nó thay thế nhanh hơn tìm kiếm ngược lại và sử dụng nó thường xuyên hơn. Nhược điểm (đó là nhỏ trong quan điểm của tôi) là bạn không thể cập nhật truy vấn tìm kiếm gốc của bạn sau khi tìm kiếm trừ khi bạn quay trở lại bằng cách "quay trở lại".Ví dụ:
lịch sử (từ trên xuống)
foo
bar
foo-ish
fubar
...
trên dấu nhắc của bạn:
> fo
báo chí up
> foo
báo chí up
> foo-ish
báo chí down
> foo
báo chí down
> fo
Chú ý: Ngay sau khi bạn thay đổi kết quả tìm kiếm và nhấn up
một lần nữa, các văn bản thay đổi trở thành truy vấn mới của bạn.
Bộ luật
const PROMPT = '> ';
// history search
let input = '';
let searchInput = input;
let searchResults = [];
let searchResultIndex = 0;
process.stdin.on('keypress', (_, key) => {
// update 'input' on changes, excluding history
if (input !== server.line && !['up', 'down'].includes(key.name)) {
input = server.line;
}
// search is initiated if a user presses the 'up' key after having inputted
if (input !== '' && (
key.name === 'up' ||
(key.name === 'down' && searchResultIndex > 0)
)) {
// reset on fresh search or if user changed input during search
if (searchInput !== input) {
searchResultIndex = 0;
// first search result is always user's input
searchResults = [input, ...server.history.filter(item => item.includes(input))];
searchInput = input;
}
const increment = key.name === 'up' ? 1 : -1;
searchResultIndex = Math.min(searchResultIndex + increment, searchResults.length - 1);
server.historyIndex = -1;
server.line = '';
process.stdout.clearLine();
process.stdout.cursorTo(0);
const result = searchResults[searchResultIndex];
process.stdout.write(PROMPT + result);
server.cursor = result.length;
server.line = result;
}
});
THƯỞNG - Thực hiện lịch sử liên tục:
const HISTSIZE = 100;
const server = repl.start({
prompt: PROMPT,
historySize: HISTSIZE,
removeHistoryDuplicates: true,
});
// load history or create file
historyFile = path.join(path.dirname(require.main.filename),
'.repl_history');
try {
fs.statSync(historyFile);
fs.readFileSync(historyFile, 'utf8')
.split('\n')
.filter(line => line.trim())
.map(line => server.history.push(line));
}
catch (e) {
console.log(e);
fs.closeSync(fs.openSync(historyFile, 'w'));
}
server.on('exit',() => {
// save history
fs.writeFileSync(historyFile, server.history.slice(0, HISTSIZE).join('\n'));
console.log('Thank you. Come again.');
process.exit();
});