Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Modules In JavaScript
Bryan C Guner
Bryan C Guner

Posted on

     

Modules In JavaScript

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
Enter fullscreen modeExit fullscreen mode
constfs=require("fs");
Enter fullscreen modeExit fullscreen mode

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 to
writeFile 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 a
poetry.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
Enter fullscreen modeExit fullscreen mode
Idonotknowwhy
Enter fullscreen modeExit fullscreen mode
Mycodeworks
Enter fullscreen modeExit fullscreen mode
Idonotknowwhy
Enter fullscreen modeExit fullscreen mode

We can use thereadFile method to read
the contents of this file. The method accepts very similar arguments to
writeFile, except that the callback may
be passed an error object and string containing the file contents. In
the snippet below, we have replaced our previous
writeFile code with
readFile:

Running the code above would print the following in the terminal:

THECONTENTSARE:
Enter fullscreen modeExit fullscreen mode
Mycodefails
Enter fullscreen modeExit fullscreen mode
Idonotknowwhy
Enter fullscreen modeExit fullscreen mode
Mycodeworks
Enter fullscreen modeExit fullscreen mode
I do not know why
Enter fullscreen modeExit fullscreen mode

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:
Enter fullscreen modeExit fullscreen mode
['My code fails',
Enter fullscreen modeExit fullscreen mode
'I do not know why',
Enter fullscreen modeExit fullscreen mode
'My code works',
Enter fullscreen modeExit fullscreen mode
'I do not know why']
Enter fullscreen modeExit fullscreen mode
ThethirdlineisMycodeworks
Enter fullscreen modeExit fullscreen mode

File I/O

Using the samepoetry.txtfile from
before:

My code fails
Enter fullscreen modeExit fullscreen mode
I do not know why
Enter fullscreen modeExit fullscreen mode
My code works
Enter fullscreen modeExit fullscreen mode
I do not know why
Enter fullscreen modeExit fullscreen mode

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
Enter fullscreen modeExit fullscreen mode
I should know why
Enter fullscreen modeExit fullscreen mode
My code works
Enter fullscreen modeExit fullscreen mode
I should know why
Enter fullscreen modeExit fullscreen mode

Refactor:

If you found this guide helpful feel free to checkout my github/gists where I host similar content:

bgoonz's gists · GitHub

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

hi

By [Bryan Guner] onMarch 8,
2021
.

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

I am a musician, former electrical engineer and current web-development student at Lambda School bootcamp!
  • Location
    ny.ny
  • Education
    The College Of New Jersey
  • Work
    Software Enginer at n/a
  • Joined

More fromBryan C Guner

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp