Node.js Basic Tutorial | Part 01

Jenny Yang
4 min readOct 15, 2020

This is one of the series I am going to write as I am learning this topic, node.js, arguably very popular backend environment where you can use JavaScript for it.

Global object

The global object is something like a window object on the browser console of JavaScript. If you print global, you can see a bunch of methods in it. There are a few methods you might use them, clearInterval, clearTimeout, setInterval, setTimeout.

__dirname and __filename

__dirname gets you an absolute path of your current value and __filename gets you an absolute path of the folder with the file name added on.

Difference between node.js and JavaScript

In node.js, DOM selectors such as querySelector wouldn’t work as in JavaScript.

Import

Importing Modules

You will separate your JavaScript file into small pieces by its functionality, so we will import modules one from another.

// variable.jsconst someVariable = 1module.exports = someVariable

So we declared this constant someVariable, then exported this variable to be able to be imported from somewhere.

Let’s import variable.js from index.js. Assume these two files are in the same directory

// index.jsconst variable = require('./variable') // require('pathName')
console.log(variable) // 1

require() is a function to import a JavaScript file, where we need to pass a relative path to the file you are going to import into.

Also, you can export several things, by export them in an object{} bracket.

// variable.jsconst someVariable = 1
const anotherValue = 'Hello!'
module.exports = {
someVariable, anotherValue
}

It will log like so in index.js

// What is printed when index.js is ran
{
someVariable: 1,
anotherValue: 'Hello!'
}

Importing operating system

You can import the operating system object of information about the current operating system.

const os = require('os')

You can console.log it to see what method the object has, to utilise it.

File System

One of the things backend code should be able to do is, abilities to read, write, delete files, and the built-in fs (file system) module in node.js allows us to do all the interactions with files.

There is a text file called mydoc.txt

// mydoc.txt
Hi! I am learning node.js!

We are going to read the file using a function readFile from fs module that is imported as below.

readFile(path to file, callback)

There are two arguments to read a file. One is the path to the file you want to read from, Another one is a callback function to specify what to do after reading the file.

// index.jsconst fs = require('fs')fs.readFile('./mydoc.txt', (err, data)=> {
if(err) {
console.log(err)
}
console.log(data.toString())
})

Note!

The functions from fs modules are asyncronous, so it takes callback function as an argument and the callback takes err and data as arguments.

when we get data from the callback, the data will get back with Buffer. If you want to see actual texts, you will need to convert the data into a string using toString().

writeFile(path to file, things to write, callback)

// index.jsconst fs = require('fs')fs.readFile('./mydoc.txt', 'text to be written', (err, data)=> {
if(err) {
console.log(err)
}
console.log(data.toString())
})

The same logic, but writeFile() takes three arguments, path, things to write to the file and callback function. Note that if the file doesn’t exist, the function will create the file we specified as the first argument for us.

mkdir(directory to create)

mkdir() will create a directory for us. If the directory already exists, it will throw an error. It is a good idea to check if the directory exists before running this function.

// check if the directory exists if not, create directory
if (!fs.existsSync('./assets')) {
fs.mkdir('./myDirectory', () => {
if (err) {
console.log(err)
}
})
} else {
fs.rmdir('./myDirectory', err => {
if(err) {
console.log(err)
}
})
}

existsSync(path to file )

existsSync() looks for the file in the path passed in, it is used to check if the file exists.

unlink(path to file, callback)

unlink() deletes a file.

Let’s delete a file if the file exists.

if(fs.existsSync('./myDoc.txt')) {
fs.unlink('./myDoc.txt', err => {
if(err) {
console.log(err)
}
console.log('file deleted')
})
}

Buffers & Streams

If the file is too large, it will take so long! we could do something whilst it is being read. Instead, we can stream the data in small chunks of data. It is the same logic when we steam music, we stream the mp3 data whilst it is being downloaded. And this packet of data in a small chunk is called a buffer.

createReadStream(file to read, encoding option)

const fs = require('fs')const readStream = fs.createReadStream('./myDoc.txt', { encoding: 'utf8'})readStream.on('data', buffer => {
console.log(buffer)
})

.on(‘data’, callback) is an event listener which is triggered whenever there is data in a Readstream.

createWriteStream(file to write)

the function to make a stream to be able to write from buffers.

const fs = require('fs')const readStream = fs.createReadStream('./myDoc.txt', { encoding: 'utf8'})
const writeStream = fs.createWriteStream('./myDoc.txt')
readStream.on('data', buffer => {
console.log(buffer)
writeStream.write(buffer)
})

Piping Streams

The code below does the same thing as above just by piping streams.

const fs = require('fs')const readStream = fs.createReadStream('./myDoc.txt', { encoding: 'utf8'})
const writeStream = fs.createWriteStream('./myDoc.txt')
// piping
readStream.pipe(writeStream)

--

--

Jenny Yang

Self-taught software engineer | Enthusiasm for programming and computer science