How to create interactive terminal like website?

You can create a static website or portfolio, that looks like terminal. But it’s much better if someone that visits the webpage, can actually type some commands and get the output like in real styled terminal.

Those real terminals are usually used on GNU/Linux systems or Mac OSX but also Windows users can use PowerShell cmd.exec or on Windows 10 WSL (Windows Subsystem for Linux) which is just Linux on Windows. It’s the most used tool for any system administrators or more advanced users.

Creating such terminal styled website is easy if you have a library that will give you the look and feel of the terminal emulator, with nice API to create commands, so you don’t need to create it from scratch. We will use JavaScript library jQuery Terminal, which gives a simple, but powerful API to create interactive terminals on any website. This article will show you, how to create simple web based, interactive terminal on any html webpage.

First, you need to create basic html page where you’ll include all dependencies:

<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="https://unpkg.com/jquery.terminal/js/jquery.terminal.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/jquery.terminal/css/jquery.terminal.min.css"/>
</head>
<body>
</body>
</html>

Then in body tag you can create your first terminal with the first command:

<script>
$('body').terminal({
    hello: function(what) {
        this.echo('Hello, ' + what +
                  '. Wellcome to this terminal.');
    }
}, {
    greetings: 'My First Terminal'
});
</script>

The output, if you type “hello Medium”, looks like this:

Terminal Screen
Simple Interactive Terminal Website

Another example command you can add to your terminal themed website, is to display an image. Following code will add command “cat”, that will display image of a kitten.

$('body').terminal({
    cat: function() {
        this.echo($('<img src="https://placekitten.com/408/287">'));
    }
});

You can also add arguments to the commands. You can add two arguments that will make specific size of the image (that will in turn create different image, this is how placekitten.com works).

$('body').terminal({
    cat: function(width, height) {
        const img = $('<img src="https://placekitten.com/' +
                      width + '/' + height + '">');
        this.echo(img);
    }
});

This will give you this output if you type command “cat” with specific size:

Image for post
Terminal that show the image of a cat

Note: make notice that there is jQuery $() call wrapper, you don’t echo just html text but you echo jQuery object. This limitation is because of security reasons. You can also use, as second argument to echo, option object with {raw: true}.

Some commands are asynchronous and take a while to calculate. Loading of the image is not instant, especially on slow networks. So you can pause the terminal while the command is processing async requests.

$('body').terminal({
    cat: function(width, height) {
        const img = $('<img src="https://placekitten.com/' +
                      width + '/' + height + '">');
        img.on('load', this.resume);
        this.pause();
        this.echo(img);
    }
}, {
    greetings: 'My First Terminal\n'
});

Another option is to return a promise from the function:

function get_image(url) {
    return new Promise(function(resolve, reject) {
        const img = $('<img src="' + url + '"'/>');
        img.on('load', () => resolve(img));
        img.on('error', reject);
    });
}$('body').terminal({
    cat: function(width, height) {
        return get_image('https://placekitten.com/' + width +
                         '/' + height);
    }
}, {
    greetings: 'My First Terminal\n'
});

And you don’t need to echo anything terminal will handle the promise. Because of this feature, you can use fetch and get output of AJAX call:

$('body').terminal({
    title: function() {
        return fetch('https://terminal.jcubic.pl')
            .then(r => r.text())
            .then(html => html.match(/<title>([^>]+)<\/title>/)[1]);
    }
}, {
    greetings: 'My First Terminal\n'
});

This command will display library’s home page title.

NOTE: if you want nice looking ASCII Art as your welcome message you can use figlet.js library see this CodePen demo.

If you want to have the same commands like in GNU/Linux or MacOSX terminal emulator, where you can add optional arguments and options, you can use function that will parse options and return nice object. The following code will show you how to do that.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

$('body').terminal({
    title: function(...args) {
        const options = $.terminal.parse_options(args);
        return fetch(options.url || 'https://terminal.jcubic.pl')
            .then(r => r.text())
            .then(html => html.match(/<title>([^>]+)<\/title>/)[1]);
    }
}, {
    checkArity: false,
    greetings: 'My First Terminal\n'
});

checkArity options is important. Without this option terminal will throw error when function has any number of arguments larger than zero (this is how ES6 variable arguments works, tree dots, terminal think that the function accept 0 arguments).

The output of this command looks like this:

Image for post
Interactive Terminal session with few commands using jQuery Terminal.

Of course, you don’t need to parse options if you have just one optional argument like in this case, you can just use one argument url:

$('body').terminal({
    title: function(url) {
        return fetch(url || 'https://terminal.jcubic.pl')
            .then(r => r.text())
            .then(html => html.match(/<title>([^>]+)<\/title>/)[1]);
    }
}, {
    checkArity: false,
    greetings: 'My First Terminal\n'
});

But parsing options are useful if you need more complex commands. You can use long options in GNU style like in previous example but also short options like -u it will be accessible in options.u variable. You can read more about parsing commands and options at this wiki page.

One more feature that you want to add is tab completion. If you set up the terminal like this (there are other options that you can find in documentation) all you need is one option:

$('body').terminal({
    title: function(...args) {
        const options = $.terminal.parse_options(args);
        return fetch(options.url || 'https://terminal.jcubic.pl')
            .then(r => r.text())
            .then(html => html.match(/<title>([^>]+)<\/title>/)[1]);
    }
}, {
    checkArity: false,
    completion: true,
    greetings: 'My First Terminal\n'
});

Now when you type “t” and press tab key on your keyboard it will complete the command “title” so you don’t need to type the whole command by hand.

You probably also want some “help” command that will list available commands.

And this is it. With this as base, you should be able to write simple terminal of your own. Features of jQuery Terminal library not discussed in this article include:

You can also take a look at the big list of creative examples and websites or single webpages that use the library in Examples Page. That include for example animations or 404 page that give commands that you can explore (like Wikipedia articles or Jargon File: also known as Hacker Dictionary, when in printed form, or as hackers would say dead tree version).

And at the end, I want to show you a demo, that give you vintage looking terminal, like the old CRT displays from beginning of computers.

Image for post

You can find the code in this CodPen Demo. You can also create the terminal in window, it don’t need to be full screen.

 

[출처] https://itnext.io/how-to-create-interactive-terminal-like-website-888bb0972288

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
1075 [ 一日30分 인생승리의 학습법] Visual Basic application on linux 졸리운_곰 2022.02.22 16
1074 [ 一日30分 인생승리의 학습법] Truffle을 이용한 DApp 개발환경 구성 file 졸리운_곰 2022.02.20 86
1073 [ 一日30分 인생승리의 학습법]LaTeX 활용해서 논문쓰장 file 졸리운_곰 2022.02.17 20
1072 [ 一日30分 인생승리의 학습법] LaTeX 초보자가 감을 잡는 것을 돕는 몇가지 팁 졸리운_곰 2022.02.17 279
1071 [ 一日30分 인생승리의 학습법] 수식 입력이 가능한 마인드맵 프로그램, 프리플레인(freeplane) file 졸리운_곰 2022.02.16 37
1070 [ 一日30分 인생승리의 학습법] Awesome Metaverse Awesome 짱!~ 메티버스 오픈소스 file 졸리운_곰 2022.02.13 11
1069 [ 一日30分 인생승리의 학습법] 제 NAS의 Docker 목록 file 졸리운_곰 2022.01.31 105
1068 [ 一日30分 인생승리의 학습법] gw basic 튜터리얼, 메뉴얼, A GW-BASIC Tutorial 졸리운_곰 2022.01.22 21
1067 [ 一日30分 인생승리의 학습법] Web Search Engine : 웹 검색 엔진 google/ naver 만들기 file 졸리운_곰 2022.01.17 28
1066 [ 一日30分 인생승리의 학습법] AILog 2 A logic programming language with probabilities and logical explanation and debugging faculities file 졸리운_곰 2022.01.16 12
1065 [ 一日30分 인생승리의 학습법] 소스 인사이트( source insight ) 사용법 file 졸리운_곰 2022.01.13 20
1064 [ 一日30分 인생승리의 학습법][메타버스란 무엇인가?] The Metaverse Has Already Arrived. Here’s What That Actually Means file 졸리운_곰 2021.12.29 23
1063 [ 一日30分 인생승리의 학습법] English to Logic, Truth-Functional Propositional Logic 졸리운_곰 2021.12.15 16
1062 [ 一日30分 인생승리의 학습법][실무행정] 기안문 공문서 기안문 작성법, 행정안전부 지침 및 시행 file 졸리운_곰 2021.12.11 42
1061 [ 一日30分 인생승리의 학습법][실무행정] 기안문 작성하기 졸리운_곰 2021.12.11 17
1060 [ 一日30分 인생승리의 학습법] 셀레니움 헤드리스 테스트를 위한 HTMLUnitDriver 및 PhantomJS file 졸리운_곰 2021.11.26 24
1059 [ 一日30分 인생승리의 학습법] 메타버스로 날개 단 오픈소스 프로젝트 file 졸리운_곰 2021.11.23 230
1058 [ 一日30分 인생승리의 학습법] Best JavaScript machine learning libraries in 2021 file 졸리운_곰 2021.11.20 8
1057 [ 一日30分 인생승리의 학습법] 프로그래밍 언어별 딥러닝 라이브러리 정리 file 졸리운_곰 2021.11.19 30
1056 [오픈소스 라이센스 상용화 라이센스 검토] [Software] 공개 SW 라이센스(GPL, LGPL, BSD) 졸리운_곰 2021.11.18 10
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED