- Watch: What is NodeJS (ignore the use of var. This is a 6 year old video)
- Read: Differences between NodeJS and the Browser
- Read: Difference between require and import
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
Activity 1: Set up a node project
- initialize a node project with the init command
- create an
index.js
orapp.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 addexport { log }
orexport 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