DEV Community

Cover image for Intro to Node.js (Part 1)
Maasa Kono
Maasa Kono

Posted on

Intro to Node.js (Part 1)

It's time to start learning Node.js! I'll share what I'm learning with the help of the amazing Net Ninja's tutorial on this topic.

What is Node.js?

Node.js is an open-source platform that runs JavaScript on a computer or server outside of the web browser. It allows for easy communication with the database with functionalities for reading, deleting and updating files.

Node.js is itself written in C++, but as a program it allows us to write in JavaScript. It runs fast thanks to the embedded V8 engine (an engine which takes JavaScript and converts it to machine code for the computer to run).

It also comes with a ton of open source packages - npm (Node Package Manager).

Installation and Usage

Node.js can be downloaded from their website: https://nodejs.org/en/.

You have the option of downloading the latest stable version or the latest version with more features but unstable.

To check if you have it installed, run the following in the terminal:

$ node -v
Enter fullscreen mode Exit fullscreen mode

This will give you the version of Node.js that's installed in your device, assuming it's there.

Everything in Node is run through the terminal. In order to run a file in Node, first be sure that you're in the directory of that specific file, and in the terminal run node followed by the name of the file:

$ node nameOfFile.js
Enter fullscreen mode Exit fullscreen mode

Global Objects

Node.js global objects are available in all modules (which are JavaScript files), which gives us access to various methods.

For those of us who use JavaScript, these global functions should look familiar:

console.log()
setTimeout()
setInterval()
clearTimeout()

Some global objects include:

__dirname
This tells us what directory we are in.

__filename
This gives us the file name as well as the directory it's in.

Function Expressions

A common pattern in Node.js is function expressions written in the following way:

const greeting = function() {
  console.log('Greetings, Earthlings.');
};
greeting();
Enter fullscreen mode Exit fullscreen mode

Modules and How to Use Them

In Node.js, we split code into logical modules - which are simply JavaScript files - and then call upon those modules when we need them. This helps with organization and results in code that is easier to understand and debug.

Let's create a module called greeting that accepts a parameter for a name to include in the greeting message. You'll notice that at the bottom we are exporting this module. We need to do this in order for other files to be able to use this module:

greeting.js

//  Here we write the function of this model:
const greeting = function(name) {
  return `Greetings, ${name}!`
}

// This export line must be included in order to make it available for use in other files
module.exports = greeting;
Enter fullscreen mode Exit fullscreen mode

Now, let's say we want to use the greeting module in the main app.js file. we'll first need to require the module that is going to be used and assign it to a variable so that we can utilize its function:

app.js

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

console.log(greeting('Goku'));
Enter fullscreen mode Exit fullscreen mode

Multiple Functions in a Module

When a module has multiple functions, the export line at the bottom is what looks a little different.

Let's go back to our original module and add another function to it:

greeting.js

const greeting = function(name) {
  return `Greetings, ${name}!`
}

const casualGreeting = function(name) {
  return 'What's up, ${name}!'
}

// The greeting property of the exports object is equal to the function
module.exports.greeting = greeting;
module.exports.casualGreeting = casualGreeting;
Enter fullscreen mode Exit fullscreen mode

Again, we just need to require the module inside of the file that we want to use, and in this way we export multiple functions from one module.

Alternatively, the same thing can be done by writing the module as follows:

greeting.js

module.exports.greeting = function(name) {
  return `Greetings, ${name}!`
}

module.exports.casualGreeting = function(name) {
  return 'What's up, ${name}!'
}
Enter fullscreen mode Exit fullscreen mode

Here is a third way to write the module performing the exact same functionalities:

greeting.js

const greeting = function(name) {
  return `Greetings, ${name}!`
}

const casualGreeting = function(name) {
  return 'What's up, ${name}!'
}

// We are creating an exports object
module.exports = {
  greeting: greeting,
  casualGreeting: casualGreeting
};
Enter fullscreen mode Exit fullscreen mode

Built-In Modules

There are several built-in core modules that can be required the same way custom modules are required.

Events Module

One such module is the Events module, which allows us to create, invoke and listen for custom events we create.

battleMode.js

// First, we require the Events module and assign it to a variable.  Node recognizes the module name because it is already built in.
const events = require('events');

// Now we can create an EventEmitter object:
const emitEvent = new events.EventEmitter();

// Create a function that will be executed when the event we created is fired:
emitEvent.on('threatened', function(fight) {
  console.log(fight);
});

// Here we are firing the event and passing in the function that is to be executed: 
myEmitter.emit('threatened', 'Ka~me~ha~me~HAAAAA!!!');
Enter fullscreen mode Exit fullscreen mode

File System Module

Another core built-in module is the File System module, which allows us to interact with with the file system on our computers. For example, we can read and write files by utilizing this module:

app.js

// As always, we are requiring the module at the top:
const fs = require('fs');

// Synchronous method for reading:
const readThis = fs.readFileSync('readThis.text', 'utf8');
  // The first parameter takes the name of the file we want to read
  // The second parameter is the character encoding so that the computer understands the JavaScript code being run

// Synchronous method for writing:
fs.writeFileSync('writeThis.txt', 'readThis');
  // The first parameter takes the file that we want to write to
  // The second parameter takes the data we want written to that file
  // If the file we are writing to does not yet exist, this line of code will create it

// Asynchronous method for reading:
fs.readFile('readThis.text', 'utf8', function(err, data) {
  fs.writeThis('writeThis.txt', data);
});
  // The first parameter takes the file we want to read
  // The second parameter is the character encoding
  // The third parameter is the callback function to fire when the process is complete
    // The callback function takes two parameters:
    // 1) Error if there is a problem with the method
    // 2) The data we are retrieving
Enter fullscreen mode Exit fullscreen mode

If we want to delete a file, simply run:

fs.unlink('fileToBeDeleted.txt')
Enter fullscreen mode Exit fullscreen mode

We can also create and remove directories with this module.

app.js

// You probably get it by now that we need to require the module first
const fs = require('fs');

// Synchronously create and remove directories:
fs.mkdirSync('someDirectory');
  // Pass in the directory name we want to create

fs.rmdirSync('someDirectory');
  // Pass in the directory we want to delete

// Asynchronously create and remove directories:
fs.mkdir('someDirectory', function(){
  fs.readFile('readThis.txt', 'utf8', function(err, data){
    fs.writeThis('./someDirectory/writeThis.txt', data);
  })
});
  // Since this is asynchronous, it takes a callback function where we read and write the file inside the newly created directory

fs.unlink('./someDirectory/writeThis.txt', function(){
  fs.rmdir('someDirectory');
});
  // Again, this is asynchronous so it takes a callback function that deletes the directory
  // In order to delete a directory, it must be empty, so we would first need to remove any file inside of it
Enter fullscreen mode Exit fullscreen mode

I hope this helps. I'm looking forward to learning more about Node.js!

Helpful Links

Top comments (3)

Collapse
 
lulungsatrioprayuda profile image
Lulung Satrio Prayuda

Thank you sir

Collapse
 
maasak profile image
Maasa Kono

My pleasure! :)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.