
Modules in Javascript
Differences between Node.js and browsers
Modules in Javascript
Differences between Node.js and browsers
There are many differences between Node.js and browser environments, but
many of them are small and inconsequential in practice. For example, in
ourAsynchronous lesson, we noted howNode's
setTimeout
has a slightly different return value froma browser's
setTimeout.
Let's go over a few notable differences between the two environments.
Global vs Window
In the Node.js runtime, theglobal
object
is the object where global variables are stored. In browsers, the
window object
is where global variables are stored. The window also includes
properties and methods that deal with drawing things on the screen like
images, links, and buttons. Node doesn't need to draw anything, and so
it does not come with such properties. This means that you can't
reference window in Node.
Most browsers allow you to reference global but it is really the same
object as window.
Document
Browsers have access to a document object that contains the HTML of a
page that will be rendered to the browser window. There is no document
in Node.
Location
Browsers have access to a location that contains information about the
web address being visited in the browser. There is no location in Node,
since it is not on the web.
Require and module.exports
Node has a predefined require function that we can use to import
installed modules like readline. We can also import and export across
our own files using require and module.exports. For example, say we had
two different files, animals.js and cat.js, that existed in the same
directory:
If we execute animals.js in Node, the program would print 'Sennacy is a
great pet!'.
Browsers don't have a notion of a file system so we cannot use require
or module.exports in the same way.
The fs module
Node comes with anfs module that
contains methods that allow us to interact with our computer'sFile
System through JavaScript. No additional installations are required;
to access this module we can simplyrequire
{.markup--code
.markup--p-code} it. We recommend that you code along with this reading.
Let's begin with achange-some-files.js
script that imports the module:
// change-some-files.js
constfs=require("fs");
Similar to what we saw in thereadline
lesson,require
will return to us a
object with many properties that will enable us to do file I/O.
Did you know?I/O is short for input/output. It's usage is
widespread and all the hip tech companies are using it, like.io.
Thefs
module contains tons of
functionality! Chances are that if there is some operation you need to
perform regarding files, thefs
module
supports it. The module also offers both synchronous and asynchronous
implementations of these methods. We prefer to not block the thread and
so we'll opt for the asynchronous flavors of these methods.
Creating a new file
To create a file, we can use thewriteFile
{.markup--code
.markup--p-code} method. According to the documentation, there are a few
ways to use it. The most straight forward way is:
The code acreate-a-nnew-file.js
(github.com)bove
will create a new file calledfoo.txt
in the same directory as ourchange-some-file.js
{.markup--code
.markup--p-code} script. It will write the string'Hello world!'
into that newly created
file. The third argument specifies the encoding of the characters. There
are different ways to encode characters;
UTF-8 is the most common and
you'll use this in most scenarios. The fourth argument towriteFile
is a callback that will be
invoked when the write operation is complete. The docs indicate that if
there is an error during the operation (such as an invalid encoding
argument), an error object will be passed into the callback. This type
of error handling is quite common for asynchronous functions. Like we
are used to, sincewriteFile
is
asynchronous, we need to utilizecallback chaining if we want to
guarantee that commands occurafter the write is complete or fails.
Beware! If the file name specified towriteFile
{.markup--code
.markup--p-code}already exists, it will completely overwrite the
contents of that file.
We won't be using thefoo.txt
file in
the rest of this reading.
Reading existing files {#aac1 .graf .graf--h3 .graf-after--p name="aac1"}
To explore how to read a file, we'll use VSCode to manually create apoetry.txt
file within the same
directory as ourchange-some-file.js
script. Be sure to create this if you are following along.
Ourpoetry.txt
file will contain the
following lines:
Mycodefails
Idonotknowwhy
Mycodeworks
Idonotknowwhy
We can use thereadFile
method to read
the contents of this file. The method accepts very similar arguments towriteFile
, except that the callback may
be passed an error object and string containing the file contents. In
the snippet below, we have replaced our previouswriteFile
code withreadFile
:
Running the code above would print the following in the terminal:
THECONTENTSARE:
Mycodefails
Idonotknowwhy
Mycodeworks
I do not know why
Success! From here, you can do anything you please with the data read
from the file. For example, sincedata
is a string, we could split the string on the newline character\n
to obtain an array of the file's
lines:
THECONTENTSARE:
['My code fails',
'I do not know why',
'My code works',
'I do not know why']
ThethirdlineisMycodeworks
File I/O
Using the samepoetry.txt
file from
before:
My code fails
I do not know why
My code works
I do not know why
Let's replace occurrences of the phrase 'do not' with the word 'should'.
We can read the contents of the file as a string, manipulate this
string, then write this new string back into the file.
We'll need to utilize callback chaining in order for this to work since
our file I/O is asynchronous:
Executing the script above will edit thepoetry.txt
file to contain:
My code fails
I should know why
My code works
I should know why
Refactor:
If you found this guide helpful feel free to checkout my github/gists where I host similar content:
bgoonz — Overview\
*Web Developer, Electrical Engineer JavaScript | CSS | Bootstrap |
Python | React | Node.js | Express |
Sequelize…*github.com
Or Checkout my personal Resource Site:
Web Dev Resource Hub
By [Bryan Guner] onMarch 8,
2021.
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse