Node Builtin Modules
Homework
- Tools
- Server-side Programming
- Read: Server-side website programming first steps on MDN
- Read: What is a web server?
- Skim: What software do I need to build a website?
- Node.js
- Builtin Modules
Morning reflection
Housekeeping
- CPNT 262 Assignment 2 marks returned
- CPNT 262 Assignment 3
1. The Node environment
Learning Objectives
- Understand the similarities and differences between the Node environment and the browser environment.
- Demonstrate a Javascript core module such as
Math
. - Log core Node objects to the console:
__dirname
__filename
this
global
- Log command line arguments to the console with
process.argv
.
Terminology
- JS Builtin Objects
- Objects that come with all Javascript runtime environments (browser, Node, etc). Examples:
Math
andDate
Materials
- Gists:
Key Takeaways
__filename
and__dirname
can be re-assigned, but please don’t.- Builtin objects do not have to be imported as they are core Javascript functionality.
process.argv
is just one of many properties and methods that come with theprocess
object but it’s the most useful.
2. Import builtin modules with require
Learning Objectives
- Log a list of all Node builtin modules to the console.
- Import a Node builtin module using
require()
.- Import the
path
builtin module. - Split a file path into its component parts with the
path
module:path.basename()
path.extname()
path.dirname()
path.isAbsolute()
path.join()
path.normalize()
- Import the
Terminology
- Node Builtin Module
- Modules that are included with the Node runtime environment. These modules need to be imported into your script but do not need to be installed with
npm
.
Materials
Gists:
Key Takeaways
- Although builtin modules come pre-installed with Node, they still need to be imported into your script with
require()
.
3. Files Access with the fs
module
Learning Objectives
- Import the
fs
builtin module.- List directory contents with
fs.readdir()
. - Asynchronously read the contents of a file and log them to the console.
- Create a new “Hello World!” file in the file system.
- Update the contents of a file.
- Delete a file from the file system.
- List directory contents with
Terminology
- File CRUD
- Create, Read, Update and Delete a file.
Materials
Key Takeaways
- Use the asynchronous version of
fs
methods whenever possible.
Open lab-time
- Refactor scripts for
process.argv
: - Data Logger - Using
fs.writeFile()
and theDate
object, build a logger into one of the above scripts so that, when it’s run from the command line:- A log file
./logs/greet.txt
(or similar) is created if it doesn’t exist; - Without overwriting the contents of the above log file, add a line to the end of the file with the date and time the script was run;
- Bonus: include the command line arguments and response as part of the log.
- A log file
Tony’s goals for Lab-Time
Dailies
- Submit today’s Codepen/repo/gist to the Dailies section (in Assessments) in Brightspace.