Node Builtin Modules

Homework

  1. Tools
  2. Server-side Programming
  3. Node.js
  4. Builtin Modules

Morning reflection

Housekeeping

  1. CPNT 262 Assignment 2 marks returned
  2. 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 and Date

Materials

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 the process 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()

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.

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

  1. Refactor scripts for process.argv:
  2. Data Logger - Using fs.writeFile() and the Date object, build a logger into one of the above scripts so that, when it’s run from the command line:
    1. A log file ./logs/greet.txt (or similar) is created if it doesn’t exist;
    2. 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;
    3. Bonus: include the command line arguments and response as part of the log.

Tony’s goals for Lab-Time


Dailies

  • Submit today’s Codepen/repo/gist to the Dailies section (in Assessments) in Brightspace.