Skip to content

Instantly share code, notes, and snippets.

@bhubr
Last active March 15, 2023 13:08
Show Gist options
  • Save bhubr/4ed8e6f7ec061e833b528d4c37bbeba5 to your computer and use it in GitHub Desktop.
Save bhubr/4ed8e6f7ec061e833b528d4c37bbeba5 to your computer and use it in GitHub Desktop.
Convert macOS colored terminal output (ANSI) to HTML

Convert macOS ANSI-colored terminal output to HTML

ansi2html is a much better solution. Why didn't I think of it before 😅🤷‍♂️?

  • Tested on macOS but should work on Linux.
  • Requires Node.js (any recent version will do).
  • Put package.json and convert.js in the same dir, and run npm i there.
  • In macOS Terminal, run shell command and redirect its stdout or stderr to a file, e.g. gls --color ~/Documents > gls-output.txt.
  • Run node convert gls-output.txt.
  • Open out.html in your browser.
// Tested with Node 16
const Convert = require('ansi-to-html');
const fs = require('fs');
const convert = new Convert();
function renderHTML(body) {
return `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>ANSI text &rarr; HTML</title>
<style>
body {
color: white;
background: black;
font-family: 'Courier New', Courier, monospace;
font-size: 13px;
}
</style>
</head>
<body>
${body}
</body>
</html>`;
}
const inputFile = process.argv[2];
if (!inputFile) {
console.error(
'ERROR: No input filed specified.\n\nUsage:\n\tnode convert <ansi text file>',
);
process.exit(1);
}
const ansiText = fs.readFileSync('typedoc-errors.log', 'utf-8');
const lines = ansiText.split('\n');
const convertedLines = lines.map((l) => convert.toHtml(l)).join('<br>');
const html = renderHTML(convertedLines);
fs.writeFileSync('out.html', html);
{
"name": "convert-ansi-html",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"ansi-to-html": "^0.7.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment