The Simplest Hello World in Node.js

Full source code available here.

I am learning Node.js and have found it a bit of a struggle to locate good, simple documentation. It feels like most people writing in the space assume a lot of existing knowledge, like you know how plenty of JavaScript, or how to effectively use web browser debug tools, have a good understanding of HTML and CSS. If you go down the rabbit hole of asynchronous programming in Node.js the writers often assume you know about the previous Node.js approach of asynchronous, try reading about async/await and you’ll be pointed to examples with promises, promisify, microtasks and callbacks, again assuming a lot of knowledge on the part of the reader.

I even asked a friend who was using Node.js to build a complex web site to write a simple Hello World program for me that I could run from the command line, but he didn’t know. This was a very experienced developer working in the industry for almost thirty years, but he started with Node.js inside a an existing web site.

If you search for how to write a “Hello world” in Node.js, you’ll find examples that setup web servers, take requests, return response, and probably use callbacks.

Because of what I perceive as a lack of documentation, I’m going write some simple blog posts about things I learn but could not find a simple example of.

To kick off, here is Hello World in Node.js.

I’m going assume you have Node and the Node Package Manager installed, and that you can run node and npm from the command line. If you do not have them installed there is plenty of help out there for that!

Hello World

Create a new directory called SimpleHelloWorld.

Open a terminal/console inside that directory.

Run -

npm init -y

This creates a package.json file, you will edit this in a moment.

Create a new file called helloworld.js.

Add a single line to the file -

console.log("Hello World");

At this point you can run -

node helloworld.js

And you will see “Hello World” printed. There you a simple Hello World program.

Let’s do one more thing, open package.json.

Replace the scripts section with -

1 "scripts": {
2    "start": "node helloworld.js"
3  },

Now you can run -

npm start

Full source code available here.

comments powered by Disqus

Related