5. JavaScript and NodeJS

Author:Peter Parente

5.1. Goals

  • Learn to read and write JavaScript code
  • Recognize the gotchas of JavaScript
  • Know what NodeJS is
  • Understand how to tap into the NodeJS ecosystem
  • Practice writing simple NodeJS applications
  • Practice using the Node Package Manager (npm)

5.2. Introduction

JavaScript is the programming language of the web. Web browser support for JavaScript has improved drastically over the past decade, giving developers the ability to create slick frontends GMail, Facebook, Instagram, and Twitter. More recently, thanks to NodeJS, JavaScript has found a foothold in creating applications outside the browser, particularly on web servers.

To get started, watch the JavaScript slidecast (~35 minutes) introducing the JavaScript programming language. The slidecast describes the following language features using short, interactive code samples:

Now watch the JavaScript Ecosystem slidecast (~25 minutes) which demonstrates how to find and install useful JavaScript libraries to save you time in building more advanced NodeJS applications. The slidecast includes demos of the following:

If time permits, review these additional pages:

5.3. Exercises

You will need to complete the Setting Up instructions before you proceed with these exercises. Once you are set up, SSH into tottbox using the vagrant ssh command from the setup instructions. Then tackle the problems below. Document what you find in a gist and share it with the TotT community later.

Important

If you are on a Windows machine, are working in your /vagrant folder, and get an error when using npm in the exercises below, include the option --no-bin-links after the name of the package. See this StackExchange question and answer for an explanation if you’re curious.

5.3.1. Guess a number

Write a JS guessing game that picks a random, secret number between 1 and 100, lets the user take up to 5 guesses, and states if the secret number is equal to, higher, lower than a guess. Read input from stdin and print to stdout.

5.3.2. Guess a word

Install the American English word list in tottbox again if you have destroyed the VM since last using it. Remember, it installs into /usr/share/dict/words.

sudo apt-get install wamerican

Now write a JavaScript program that chooses a random word from the list, reveals it one random letter at a time to the user, and asks the user to input guesses.

5.3.3. Read and visualize

JSON is a lightweight, text-based, human-readable, open data exchange format. It is commonly used for communication between a web server backend and application frontend. It is also a valid subset of the JavaScript language.

Download this list of U.S. capitals to tottbox. The list is in JSON format with the capitals sorted east to west by longitude.

Write a JS program to compute the longitude distance between each capital and the next. Output the distances to stdout along with some summary stats for the entire dataset (e.g., min distance, max, mean, median, standard deviation). Try to find a creative way to represent the relative magnitude of the distances in your output.

5.3.4. Fetch a quote

I Heart Quotes provides a web service for fetching random quotations. You can test it by visiting http://www.iheartquotes.com/api/v1/random in your browser.

Write a JS program that pulls a quote from this site and displays it on stdout in the terminal. (Hint: Look at the http module in the NodeJS standard library, particularly the request() function).

5.3.5. Serve quotes

Write a tiny web server using the NodeJS http module that fetches a quote from I Heart Quotes and returns it to the requesting client. Run the web server in tottbox on port 9000 and test it by pointing Google Chrome on your laptop to http://192.168.33.10:9000. (Hint: Google for or look on the NodeJS site for the few lines of code you need to create a web server in NodeJS.)

5.3.6. Paint a rainbow

Make a new directory in your shared tottbox folder. Change to that directory and use npm to install the colors module locally into that folder.

mkdir -p /vagrant/js/rainbow
cd $!
npm install colors

Google for nodejs colors. Read about the features the module provides and view the examples. Now write a JS program that iterates over all the colors provided and outputs their names in their respective colors.

5.3.7. Show time til “freedom”

Make another folder and install the moment module using npm. Look at the university calendar for the date that classes end this semester. Write a JS program using moment that output a human friendly description of the time left til classes end. (Hint: Look at moment.duration and its functions.)

5.3.8. Handle args

In the same “freedom” folder, npm install optimist. Find its documentation and study the examples. Now use it to add support for command line arguments that let the user specify:

  1. The date of interest, with the end of semester date as the default.
  2. If the output should be humanized or not, with yes, humanize, as the default.

5.3.9. Make it repeatable

If you completed the two exerices directly above, your application now depends on moment and optimist. Write a package.json file that installs these prerequisites when you type npm install. (Hint: Refer to the interactive package.json cheatsheet).

5.3.10. Analyze sentiment

Sentiment analysis is an attempt to determine subjective information from text. For example, identifying the polarity of a statement, whether it is a positive or negative opinion, has almost become synonymous with with “doing sentiment analysis.”

Make another directory and install the natural NPM module. Find its documentation, read its summary, and focus on the section about classifiers.

Download the sample movie reviews polariy dataset v2.0 and extract it in the folder you created:

cd /vagrant/whatever_folder_you_created
wget http://www.cs.cornell.edu/people/pabo/movie-review-data/review_polarity.tar.gz
tar xzf review_polarity.tar.gz

Spend a moment poking around in the contents of the extracted data. Then, write a JS program that reads in 50 positive reviews, 50 negative reviews, and trains a Naive Bayes classifier using them. Use the classifier example in natural as a guide. After training the classifier, test the classifier against a few more positive and negative examples from the dataset or your own custom test cases.

5.3.11. Explore common libs

Use NPM to install the underscore and async modules, two very popular JavaScript libraries. Read their documentation. Come up with an example of where one or both might be effective. What do the alternatives look like? Why might you prefer use of these libraries?

5.3.12. Explore node_modules

Install a bunch of modules using NPM. Poke around in the node_modules directory. Read about how NPM works on the web. What can you deduce about how NPM and NodeJS manage packages and their dependencies?

5.4. Projects

If you want to try your hand at something larger than an exercise, consider one of the following.

5.4.1. Markdown slides

Write a utility that can take a Markdown document and convert it into a complete reveal.js slidedeck without forcing the user to write all of the boilerplate. Support slides, subslides, and incremental builds. Decide and document what valid markup will indicate these features.

5.4.2. .jsjobs cron replacement

Write a JavaScript program that executes a run() function exported by any JS module located in a folder named ~/.jsjobs on an interval also exported by each module. Make the program support millisecond intervals to start, but then extend it to support human-readable intervals using a library like Moment.js.

5.5. References

Eloquent JavaScript
Introduction to programming in JavaScript
JavaScript on the Mozilla Developer Network
Comprehensive reference for all things JavaScript
NodeJS Docs
API reference for the NodeJS standard library
JavaScript Style Guide
A JS style guide from Airbnb
Principles of Writing Consistent, Idiomatic JavaScript
Another JS style guide