Creating a Lorem Ipsum Generator with Node and Express

Written by robertcooper_rc | Published 2017/11/12
Tech Story Tags: javascript | nodejs | expressjs | lorem-ipsum-generator | lorem-ipsum

TLDRvia the TL;DR App

A few months ago, I made a lorem ipsum app that would jumble together technology related words into sentences and paragraphs. After watching the latest season of Stranger Things, I decided to change my application to use quotes from the Stranger Things series and I renamed the app Stranger Ipsum.

The application is built with Node.js and Express. It’s a simple application that only has one page, but I thought I’d explain the main pieces of the application, since it may be helpful for those learning Node and Express. If you follow along with the steps outlined below, you should be able to create your own simple lorem ipsum application.

For those who aren’t already familiar, Node.js is a server framework and Express is a web framework for Node. Basically, Express makes using Node a bit easier since you don’t have to write as much code to get things working the way you want. Express also has some great documentation you can reference.

If you’d like to view the final version of my lorem ipsum app which includes all of the code described below and more, you can view it live or you can take a look at the code on Github.

Getting started

Before doing anything, make sure you’ve got npm and node installed on your computer. Then create a project directory (mkdir project-name) naming it whatever your heart desires. Once you’ve done that, navigate inside your project directory using your terminal (cd project-name) and initialize a **package.json** file with the command npm init -y. The init command initializes a new **package.json** file and the -y option accepts all the default parameters.

Before creating any files, make sure to install Express from npm with the following command: npm install express.

Once you’ve done that, create your main application file inside of your project directory and name it **app.js**. Below is all the code that goes into your **app.js** file:

I’ve got comments in the code to help with understanding, but I’ll explain it further. The variables express and app defined at the top of **app.js** are necessary in order to create an Express application. The app variable is an object created by Express and it has many different methods we can call.

The routes variable holds our application routing logic, which is defined in **router.js**. I’ll go over that later.

The hostname and port variables include information about where the application server can be found. 127.0.0.1 refers to your localhost and 3000 is a port number I chose to serve my application on.

app.use(express.static('public')) tells Express where to look when serving static assets (such as images, html, and css files). In this case, static assets will be saved in the **/public** folder.

app.use(routes) tells Express to use the routes defined in the routes variable we defined earlier.

Finally, app.listen() is used to specify the port on which our application is running and begin accepting connections to the application. In our case, this allows us to view the application at localhost:3000 in a browser window.

index.html

Next, let’s create the **index.html** file. Since we specified our static assets directory as **/public**, make sure to create a directory named **public** and add in a blank **index.html** and **styles.css** file in the folder.

Your project directory should now look like this:

/project-name  /public    - index.html    - styles.css  - app.js  - package.json

Alright, we need 5 main things in our **index.html** file:

  1. A link to our stylesheet (**styles.css**)
  2. A title
  3. A description
  4. A form that will accept the number of paragraphs to be generated
  5. A <div> that will contain the generated lorem ipsum text

Here is what the **index.html** file looks like with all those pieces in place.

I’m not going to go over the styling of the app with CSS. You can add whatever styles you’d like so your app has its own bit of flair.

Application Routes

Our app routes will be organized in **router.js**. We will need to setup 2 routes:

  1. a GET route for the main application web page
  2. a POST route when the user inputs the number of paragraphs they would like to generate

The GET route will serve our **index.html** page and our POST route takes the user input and passes it into a function that will generate the required number of paragraphs of text. Here is how the **router.js** file should look like:

The loremIpsum variable defined at the top is an object that is created by a constructor function we will define later in **generator.js**. The querystring module is required to parse strings to key/value pairs in the POST route and the fs module is required to get the contents of different files in our application (fs stands for file system).

Variable declarations in router.js

We are creating a router instance from the express.Router class in order to properly manage our routes and their handlers (a route handler is the function that gets executed for a specific route). Our first route definition is the GET route to our main application page (i.e. the root or / route). The router handler for the root route sends the contents of **index.html** to the client.

GET route defined in router.js

Our second route definition is the POST route which deals with the input value submitted by the user. The input value is an integer that specifies the required number of paragraphs to generate. The callback to request.on() gets called once data is received from the client and that data is stored in the inputValue variable. Once the data comes in, we convert it to a readable string using the .toString() method. We then store the numerical value of the user input in a variable called numberOfParagraphs with the help of querystring.

Next, we generate and store lorem ipsum text in a variable called loremIpsumText. The generation of the lorem ipsum text will be explained in the next section. Once we’ve got the text, we load the contents of index.html into a variable and replace the placeholder <div> with the lorem ipsum text. The modified **index.html** file then gets sent to the client and Voila!

POST route defined in router.js

Don’t forget to add the module.exports = router; statement at the bottom of **router.js**. This allows us to require the file inside of **app.js**.

Generating the Lorem Ipsum

The way I’ve setup my lorem ipsum application is to have a bunch of quotes stored in an array and then form a paragraph by randomly selecting quotes from the array. Create a **generator.js** file and add the following code to that file:

What’s going on in this file is that I am creating a constructor function called GenerateNewText() which will create an object with a property called sentences and methods called getRandomSentence, getParagraph, and getAllParagraphs. An object called loremIpsum is created from the GenerateNewText() constructor function and it is exported at the bottom of the file so it can be required in **router.js**.

The sentences property contains an array of quotes that will be used to build up a paragraphs of text.

The sentences property stores the strings that will be generated in our lorem ipsum app

I’m not going to explain what each method in GenerateNewText() does, since the names I’ve assigned to the methods explain their function. The getAllParagraphs method is called in **router.js** with the number of paragraphs passed in as an argument.

Run the App

Alright, you should have everything in place to run your own application in the browser. In your terminal, navigate inside of your project folder and run the application using node app.js. If all goes according to plan, you should be able to go to your browser at localhost:3000 and see your app running. Try inputing a number of paragraphs and hit Generate. You should see your page refresh with the randomly generate text appearing at the bottom!

Here’s what my page looks like when I follow the steps I’ve outlined above (with a few styles applied to the app):

The result of following the above steps to create your own lorem ipsum app

Conclusion

As you can see from the picture above, the result could use some more styling to make the app look better. The app could also use more variety in the sentences that are outputted. You would have to add more items to the array of strings inside of **generator.js**. There’s a bunch of other stuff that could be done to improve the application. There is a great site that lists a whole bunch of popular lorem ipsum apps you can check out to draw inspiration from.

If you’ve created a lorem ipsum app, please share it in the comments since I’d love to check it out!

If you found this article interesting and web development interests you, consider following me on Twitter, Github, or LinkedIn.


Published by HackerNoon on 2017/11/12