Getting Started with Server-Side Scripting using Node.js

Vinayak Tekade
Coder’s Capsule
Published in
7 min readMar 18, 2021

This article is the ninth part of Week of Web(#WOW). If you don’t know what #WOW is here’s a card to it.

In this article, we will learn server-side scripting using Node.js along with Node.js runtime and Node.js modules.

What is Node.js?

Node.js is not a programming language but rather a JavaScript runtime environment that means it allows developers to JavaScript on servers.

This will be much clearer when we know the history of JavaScript

When JavaScript first came out in the 1990s, it was designed as a simple scripting language to run in the browser. As the web platform evolved, there were many developments in JavaScript and in 2009 we got the initial release of Node.js. This was a big revolution as until now it was impossible to write server-side code. Most servers were written in Java or PHP earlier and now it was possible to write a full-stack application in a single language.

And that is what Node.js is. It makes writing server code in JavaScript possible where earlier it could be only written in a web browser.

What does Node.js do on a basic level?

So let us say you visit a URL on the internet that points to your web server. When this request is received by your web server Node.js kicks in to handle the request and reads a file present in your web server and then it responds back to your application which can then display the file.

How to use Node.js?

The easiest way to see Node.js in action is by using it in REPL mode. REPL stands for Read Evaluate Print Loop.

Just type node into the command line to enter this mode

node

This mode allows you to run JavaScript code on the fly and will immediately print out the result.

This is nice to test things out. But we would actually like to run JavaScript files in it. So press ctrl+c twice to come out of REPL mode.

Now create a new file called index.js in the root of your directory and add some JavaScript commands to it.

node index.js

Or since most of the times, server-side code lives in a index.js file. (don’t ask me why it’s just become a norm now, some other commonly used entry points are app.js and server.js). Just point node to your project directory

node .

Congratulations you built your first node app!

Node.js Runtime

Node.js is an asynchronous event loop driven runtime. That means it is not very heavy on your server and does not run too many processes parallelly. But this comes with the drawback of it can not run CPU intensive task.

npm

When you installed node earlier it also installed npm. Which is a tool we can use to install remote packages to use in your own code.

The first thing to do here is to initialise our repository to use npm.

npm init -y

The -y flag is used to enter all default properties.

Now a package.json file will be created which will keep a track of all the packages you have installed.

To install a package we use the following command

npm i express

Now you will notice a folder called node_modulescreated where all your installed files are present. You can access the files present here but if you find yourself writing code here, you are probably doing it wrong.

Also, the package.json file is updated with express present inside the dependencies object. This is helpful because in case you want to reinstall packages you just need package.json file. To reinstall packages just run this command where the package.json file is present.

npm i

Node.js Modules

Photo by Clarissa Watson on Unsplash

Importing and Exporting Modules

Let's we have two files one is index.js and the other one is person.js . The person.js file has all the details of a person and we need this information in our index.js.

This is content inside our person.js

const person = {
name: "Vinayak Tekade",
age: 21,
};

We need to export the person object, so we write this in the end of person.js

module.exports = person;

To import a module in node.js we use the require method. We will use this to grab information from person.js

const person = require('./person');

and then work with the person object.

const greet = (e) => {
console.log(`I'm ${e.name} and I'm ${e.age} years old`);
};
greet(person);

This feature can be used to import inbuilt modules as well

Path Module

The path module is used to get information about your file and work with paths of files.

const path = require("path");// Base file name
console.log(path.basename(__filename));
// Directory name
console.log(ath.dirname(__filename));
// File extension
console.log(path.extname(__filename));
// Create path object
console.log(path.parse(__filename));
// Concatenate path
// ../test/hello.html
console.log(path.join(__dirname, "test", "hello.html"));

File System Module

The file system module is used to work with files and folders in your web server.

const fs = require("fs");
const path = require("path");
//Create folder
fs.mkdir(path.join(__dirname, "/test"), {}, (err) => {
if (err) throw err;
console.log("folder created ...");
});
// Create and write to file
fs.writeFile(
path.join(__dirname, "/test", "hello.txt"),
"Hello World!",
(err) => {
if (err) throw err;
console.log("file written ...");
}
);
//Append to file
fs.appendFile(
path.join(__dirname, "/test", "hello.txt"),
" I love Node.js",
(err) => {
if (err) throw err;
console.log("file written ...");
}
);
// Read file
fs.readFile(path.join(__dirname, "/test", "hello.txt"), "utf8", (err, data) => {
if (err) throw err;
console.log(data);
});
// Rename file
fs.rename(
path.join(__dirname, "/test", "hello.txt"),
path.join(__dirname, "/test", "helloworld.txt"),
(err) => {
if (err) throw err;
console.log("file renamed");
}
);

Operating System Module

The operating system module is used to get information about your web severs’s system.

const os = require("os");// Platform
console.log(os.platform());
//CPU Architecture
console.log(os.arch());
// CPU Core Info
console.log(os.cpus());
// Free Memory
console.log(os.freemem());
// Total Memory
console.log(os.totalmem());
// Home Directory
console.log(os.homedir());
// Uptime
console.log(os.uptime());

URL Module

The URL module is used to get information from an URL and also make changes to it.

const url = require("url");const myUrl = new URL("http://mywebsite.com/hello.html?id=100&status=active");// Serialized URL
console.log(myUrl.href);
console.log(myUrl.toString());
// Host (root domain)
console.log(myUrl.host);
// Hostname (does not get port)
console.log(myUrl.hostname);
// Pathname
console.log(myUrl.pathname);
// Serialized query
console.log(myUrl.search);
// Params object
console.log(myUrl.searchParams);
// Add param
myUrl.searchParams.append("abc", "123");
console.log(myUrl.searchParams);
// Loop through params
myUrl.searchParams.forEach((value, name) => console.log(`${name}: ${value}`));

Events Module

The events module is used to create event listeners when an Event Emitter class is called.

const EventEmitter = require("events");// Create class
class MyEmitter extends EventEmitter {}
// Init object
const myEmitter = new MyEmitter();
// Event listener
myEmitter.on("event", () => console.log("Event Fired!"));
// Init event
myEmitter.emit("event");

HTTP Module

The HTTP module is used to create a request-respond pair server and manage the server.

const http = require("http");// Create server object
http
.createServer((req, res) => {
// Write response
res.write("Hello World");
res.end();
})
.listen(5000, () => console.log("Server running..."));

How does a functional Node.js server look like?

Now let's see how all the modules discussed are used to create an actual very basic server.

Here we have imported all the required modules. Then created a server using the HTTP module. Inside the server, we are fetching files from the public folder based on their file name and file extension. The content type is set using the file extension. After that, we just have to add an exception of when the file is not found we set the status code to 404 and display user a not found page.

And developers have to write this code repeatedly with more or less the same conditions. And therefore there's a need for a framework. There's a popular framework for writing Node.js servers called Express.js which makes this job much simpler.

The important concepts remain in Node.js and many people skip learning Node.js and directly start with Express.js just for the sake of simplicity. But a framework will still remain a framework built over the concepts of what it’s making easier.

Photo by Sigmund on Unsplash

In the next article, we will discuss express.js and build our application using it.

This is Vinayak Tekade from Coder’s Capsule in collaboration with Developer Student Clubs Amrita School of Engineering Bengaluru signing off.

Follow me on LinkedIn and Twitter.

Looking forward to learn, teach and grow together. Check us out on Instagram for more similar content.

--

--

Vinayak Tekade
Coder’s Capsule

A young developer looking forward to learn, teach and grow together. Contact me at @VinayakTekade