Reader small image

You're reading from  Hands-on JavaScript for Python Developers

Product typeBook
Published inSep 2020
Reading LevelIntermediate
PublisherPackt
ISBN-139781838648121
Edition1st Edition
Tools
Right arrow
Author (1)
Sonyl Nagale
Sonyl Nagale
author image
Sonyl Nagale

Chicago-born, Iowa-raised, Los Angeles-seasoned, and now New York City-flavored, Sonyl Nagale started his career as a graphic designer focusing on web, which led down the slippery slope to becoming a full-stack technologist instead. With an eye toward the client use case and conversation with the creative side, he prides himself on taking a holistic approach to software engineering. Having worked at start-ups and global media companies using a variety of languages and frameworks, he likes solving new and novel challenges. Passionate about education, he's always excited to have great teachable moments complete with laughter and seeing the Aha! moments in students eyes.
Read more about Sonyl Nagale

Right arrow
What Is Node.js?

Now that we've examined the use of JavaScript on the frontend, let's dive into its role in the "JavaScript everywhere" paradigm using Node.js. We discussed Node.js in Chapter 2, Can We Use JavaScript Server-Side? Sure!, so now it's time to dive deeper into how we can use it to create rich server-side applications.

The following topics will be covered in this chapter:

  • History and usage
  • Installation and usage
  • Grammar and structure
  • Hello, World!

Technical requirements

History and usage

First released in 2009, Node.js has been widely adopted in the industry by major corporations and smaller companies alike. There are literally thousands of packages available for use in Node.js, creating a rich ecosystem of users and a community of developers. As with any open source project, community support is crucial to the adoption and longevity of the technology.

From a technical standpoint, Node.js is a runtime environment in a single-threaded event loop. What this means in practice is that it can handle thousands upon thousands of concurrent connections without the overhead of switching between contexts. For those who are more familiar with other architectural patterns, a single thread might seem counterintuitive, and it used to be held up as an example of Node.js's perceived breakpoint. However, it can be argued that the stability and reliability of a Node.js system has shown this paradigm to be sustainable. There are ways to augment a server's capacity...

Installation and usage

The easiest way to install Node.js is to use the installers provided for you at https://nodejs.org. These packages will guide you through the installation of Node.js on your system. Be sure to also install npm, Node's package manager. You can refer to Chapter 3, Nitty-Gritty Grammar, for more details on installation.

Let's give it a go:

  1. Open a Terminal window.
  2. Type node. You will see a simple > to indicate that Node.js is running.
  3. Type console.log("Hi!") and hit Enter.

It's really as simple as that! Exit the command prompt either by hitting Ctrl + C twice or typing .exit.

So, that's fairly basic. Let's do something a bit more interesting. Here's the contents of chapter-11/guessing-game/guessing-game.js:

const readline = require('readline')
const randomNumber = Math.ceil(Math.random() * 10)

const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});

askQuestion()

function askQuestion() ...

Grammar and structure

The great thing about Node.js is that you already know how to write it! Take this for example:

JavaScript

Node.js

console.log("Hello!")

console.log("Hello!")

That's not a trick: it's identical. Node.js is syntactically almost identical to browser-based JavaScript, right down to the fight between ES5 and ES6, as we've discussed previously. In my experience, there is still a preponderance of ES5-style code in use with Node.js, so you will see code with var instead of let or const, as well as a healthy use of semicolons. You can review Chapter 3, Nitty-Gritty Grammar for more information on these distinctions.

In our guessing game example, we see one thing that is new to us – the first line:

const readline = require('readline')

Node.js is a modular system, which means that not all parts of the language will be brought in at once. Rather, modules will be included when the require() statement is...

Hello, World!

Create a new directory called hello-world and initialize a node project with npm init, similar to how we did previously. In Chapter 13, Using Express, we'll work with Express, a popular web server for Node.js. However, for now, we'll use a very bare-bones method of creating a page.

Start off your index.js script as follows:

const http = require('http')

http.createServer((req, res) => {
res.writeHead(200, {'Content-Type': 'text/plain'})
res.end("Hello, World!")
}).listen(8080)

As with fs and readline, http is built in to Node, so we don't have to use npm install to get it. Rather, this will work out of the box. Add a start script in your package.json file:

"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
},

Then fire it up!

Figure 11.2 - Executing npm start

OK, our output isn't super helpful, but...

Summary

We've learned in this chapter that Node.js is a full-fledged programming language, capable of doing pretty much anything backend-related. We'll get into databases with Node.js in Chapter 18, Node.js and MongoDB, but, for the meantime, we can rest assured that it can do what we'd expect from a modern programming language.

The great thing about Node.js is that its grammar and structure is regular JavaScript! A few of the terms are different, but all in all, if you can read and write JavaScript, you can read and write Node.js. As with every language, there are differences in terminology and usage, but the fact is that Node.js and JavaScript are the same language!

In the next chapter, we'll discuss Node.js and Python and where certain choices make sense for using one versus the other.

Further reading

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Hands-on JavaScript for Python Developers
Published in: Sep 2020Publisher: PacktISBN-13: 9781838648121
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Sonyl Nagale

Chicago-born, Iowa-raised, Los Angeles-seasoned, and now New York City-flavored, Sonyl Nagale started his career as a graphic designer focusing on web, which led down the slippery slope to becoming a full-stack technologist instead. With an eye toward the client use case and conversation with the creative side, he prides himself on taking a holistic approach to software engineering. Having worked at start-ups and global media companies using a variety of languages and frameworks, he likes solving new and novel challenges. Passionate about education, he's always excited to have great teachable moments complete with laughter and seeing the Aha! moments in students eyes.
Read more about Sonyl Nagale