NodeJS and Built in Modules

null

A Closer Look at NodeJS

We’ve installed node packages and set up node projects. But we haven’t gotten into the fact that node is a runtime environment

  • Every file in a node application is considered a module
  • Variables and Functions in each file are scoped to that file

NodeJS Slides

Activity 1: Set up a node project

  • initialize a node project with the init command
  • create an index.js or app.js file with a console.log() to make sure your scripts work
  • also set up git and add a .gitignore (hiding node_modules)
  • set up a start command in your scripts

Activity 2: Create a module

  • Create a logger.js file and in it write a custom logger function that takes a variable
  • set it to module exports module.exports module.exports = log`
  • require it in the app.js file `const log = require(‘./logger’)
  • use the logger in the app file

Activity 3: Refactor for es6 imports

  • es6 import/export syntax is another way to use modules
  • add "type": "module" to your package.json file
  • remove module.exports = log and add export { log } or export default infront of the function
  • use import {log} from './logger' syntax to import it
  • try setting an alias with “as”

Activity 4: Built in Modules fs

  • Use fs.writeFile() to add contentent to a: json, txt, and md file
  • use fs.readFile() to log the content to the console