This tutorial is a comprehensive guide consisting of 15 chapters designed to teach
beginners in node.js. It is assumed that learners have a basic knowledge of
JavaScript. Unlike vanilla JavaScript which runs on browsers, Node.js runs on
servers. Therefore, we interact with the back end of the application on a terminal
window, not the browser. While there are no distinct differences between Node.js
and Vanilla JS, Node.js has common core modules that Vanilla JS lacks. These
modules relate to the operating system, file system, and other server functions.
Common JS Modules
OS Module
FS Module
HTTP Module
Mime Module
URL Module
Path Module
These modules are imported using Common JS import syntax.
While there are differences in module imports with the Vanilla JS, efforts are
being made to bring a uniform syntax.
In Node.js, we can use a common core module called "path" with a common JS import.
We can also reference filenames within this path. For example:
path.join(__dirname, 'folder', 'filename')
path.resolve(__dirname, '../folder/filename')
path.extname('filename.txt')
Additionally, we can pull in packages created by other developers. We will cover
this in more detail in a future tutorial. To import functions that we have defined,
we need to define "math" as "require":
const math = require('math');
However, since "math" is not a common core module, we must include the file
extension when referencing it:
const math = require('math/math.js');
It's worth noting that Node.js is missing some APIs available in vanilla
JavaScript, such as "fetch". However, we can always pull in packages to gain access
to these APIs. In our next tutorial, we will cover reading, writing, creating,
updating, and deleting files using the file system common core module.
Visual Studio Code is open with an empty index.js file and a files directory in the
file tree.
We're going to start by importing the fs common core module here using CommonJS
imports:
const fs = require('fs');
After that, let's go ahead and read that starter file so we need to specify the
file name:
fs.readFile('starter-file.js', (err, data) => { if(err) throw err;
console.log(data);});
In node, the functions or methods you'll find from node will be asynchronous. This
is direct from the node documentation. So let's go ahead and throw an error on
purpose:
fs.readFile('hello', (err, data) => { if(err) throw err;