How I made Reddit in the Console
Tags: showdev, justforfun
Published: 2019-06-06 16:57:52

---
title: How I made Reddit in the Console
published: true
description: Using console quirks to make something fun
tags: showdev, justforfun
cover_image: https://thepracticaldev.s3.amazonaws.com/i/62co128q8f0qmxzwqorh.png
---

Sometimes it's fun to take technologies and use them in ways they obviously weren't meant to be used. Besides being fun, it also helps you learn about the quirks of the technology you're using.

The goal of this project for me was to learn more about the console and some of the lesser known features by re-making Reddit.  Even though I've been console.logging my whole life, I found several console features I never even knew about through this process!

## Getting the data
I chose to implement Reddit instead of a different social media site because it's amazingly easy to get data from Reddit.

Want to get the json data for /r/all? Simply append .json to the url:
https://www.reddit.com/r/all.json

Beautiful, thanks Reddit. 

Now that we have an API endpoint, we can fetch the data:

```javascript
function getPosts(currentSub){
  let url = "https://www.reddit.com/r/" + currentSub + ".json";
  fetch(url)
    .then(function(response) {
      return response.json();
  })
  .then(function(json) {
    parsePosts(json["data"]);
  });
}
```

Our getPosts function will take a subreddit name so we can fetch posts from any subreddit in the console!

## Printing images

Reddit is mostly images, and so our console version of Reddit should support images too!

Going into this project I knew that it was possible to print images to the console, but I had no idea how.

After some research I found out: It's black magic.

It turns out that if you put "%c" in your console.log message, then you can pass a second parameter with styles that will be added to the message. 

For example:
console.log('%c IM HUGE', 'font-size: 48px;');

will show up as:
![](https://thepracticaldev.s3.amazonaws.com/i/e7gw0k6i93fyybwmv993.JPG)

So how do we use this feature to print images? The answer is the background-image property! But images don't behave as expected in the console. For instance the following 

```javascript
console.log('%c', 'background-url=url(./walrus.jpg) no-repeat;');
```

Will appear as:

![](https://thepracticaldev.s3.amazonaws.com/i/w6pysa2lsrgi6zi8ghb3.JPG)

To get the image to display properly, we'll have to add padding to our style. 

```javascript
console.log('%c ', 'padding: 125px; background:url(./walrus.jpg) no-repeat;');
```

Now it will display correctly:

![](https://thepracticaldev.s3.amazonaws.com/i/0zrysrpmakbi1bxdqltj.JPG)

Now this is great, but we can't hardcode the padding on the styles because the images from Reddit will have different dimensions. To fix this we'll need to add different padding on each image depending on the image size. 

We can do that with some Javascript:

```javascript
function logImage(url) {
    var img = new Image();

    img.onload = function() {
        let width = this.width;
        let height = this.height;

        //Resize if needed
        if (this.width > 600) {
            width = 600;
            height = 600 * (this.height / this.width);
        }

        var style = getStyle(width, height);
        console.log("%c", style + "background: url(" + url + ");");
    };

    img.src = url;
}


function getStyle(width, height) {
	return "padding: " +
               Math.floor(height/3) + "px " +
               Math.floor(width/2) + "px; line-height: " +
               height/3 + "px;"
}
```
We also scale the image so that the maximum width of the image is 600px which provides a better viewing experience. Also line-height is added to make sure that the image stays centered. 

Next, let's print the actual images from Reddit. 

Our Reddit JSON data contains a URL for each post. Using that we can check if the URL is an image by checking if it contains an image extension (.png, .jpg, etc). If it does, then we console.log the image.

It even works for gifs!

![](https://thepracticaldev.s3.amazonaws.com/i/c9h3qwiowfk9zqhyvcyp.gif)

To add more context, let's add more information like the author and upvote count.

```javascript
console.log('%c ' + "/r/" + postData["subreddit"] + 
                    " · Posted by u/" + postData["author"] +
                    " · "  + postData["score"] + " upvotes", 
                    "font-size: 14px;");
```

Here's what it looks like now:

![](https://thepracticaldev.s3.amazonaws.com/i/xhprayxzoq8dj1pp7swt.JPG)

Beautiful! Maybe this is how Reddit was meant to be experienced.

All that's left is to add the comments. 


## Adding the Comments

Sadly the original API endpoint we called does not include comments. So we will have to include another API call for each post to get the comments. But thankfully Reddit makes this process easy too. We just have to use the permalink given in the first API call to call another endpoint:

```javascript
function getComments(permalink, done){
  let url = "https://www.reddit.com" + permalink + ".json";
  
  fetch(url)
    .then(function(response) {
      return response.json();
  })
  .then(function(json) {
     parseComments(json);
     done();
  });
}
```

And just like that, we're able to get comments for all our posts!

Now we just have to figure out to display them. We could simply console.log all the comments, but considering a Reddit post can get hundreds of comments, simply printing all the comments would be a bad user experience.

Luckily, the console has another lesser known feature. Using console.group() and console.groupEnd(), we can create collapsable groups inside the console.

For example:

```javascript
console.group("This is a group");
console.log("I'm inside the group!")
console.groupEnd();
```

Will look like this inside the console:

![](https://thepracticaldev.s3.amazonaws.com/i/cdv5npbs2ebdp7biuh42.JPG)

Using this, we can now make our comments collapsed by default:

![](https://thepracticaldev.s3.amazonaws.com/i/urgnprk2rulfkttrx1lc.JPG)

But wait that's not all! The console allows you to nest groups inside each other. So we can actually display the Reddit comments in a threaded fashion just like the real Reddit!

Here's how it works:

```javascript
function addComment(comment){
  if(!comment["body"]){
    return; 
  }
  console.group(comment["author"] + " · " + comment["score"] + " upvotes");
  console.log(comment["body"]);
  if(comment["replies"]){
    parseReplies(comment["replies"]["data"]["children"]);
  }
  console.groupEnd();
}

function parseReplies(replies){
   for(let x = 0; x < replies.length; x++){
     addComment(replies[x]["data"]);
   }
}
```
For each comment, we create another console group with the author name and the number of upvotes for that comment. We then recursively do the same thing for all the replies to that comment and only call console.groupEnd() once all the replies have been added. 

The result looks just like normal Reddit comments, and comment threads are even collapsible!

![](https://thepracticaldev.s3.amazonaws.com/i/kovrlfozieo84p28tsb5.JPG)

Putting it all together here's the final product:

{% twitter 1125097314505375744 %}

[Click here to see the full code](https://glitch.com/~console-reddit)
[And click here to see it in action!](https://console-reddit.glitch.me/)

This project was a blast and I learned more about the console than I thought I ever would. Feel free to remix it and add more features.

Also if you like silly & fun projects, [I have more on my Twitter!](https://twitter.com/nealagarwal)