🪴 yshalsager's Digital Garden

Search

Search IconIcon to open search

Node.js Module System

Last updated Oct 30, 2022

المعرفة:: NodeJS
الحالة:: #ملاحظة_مؤرشفة
المراجع:: The Complete Node.js Developer Course 3rd Edition, coggro’s Notes, anuragkapur’s Notes


# Importing Node.js Core Modules

1
console.log('Hello Node.js!')  

# Core Modules and require

1
2
3
const fs = require('fs');  
  
fs.writeFileSync('notes.txt', 'Hello Note.js!');  

^fffd7a

1
fs.appendFileSync('notes.txt', 'Added text');  

^e6ac24

# Importing Our Own Files

1
console.log('utils.js!')  
1
2
const checkUtils = require('./src/utils.js');  
checkUtils();  

# Exporting from Files

1
2
3
4
5
const getNotes = function () {  
    return 'Your notes...'  
}  
  
module.exports = getNotes  
1
2
3
const getNotes = require('./notes.js')  
const msg = getNotes()  
console.log(msg)  
1
2
3
4
5
6
7
8
9
// file 1  
// ...  
export { utilslog, name }  
// or  
module.exports = {getNotes, addNotes}  
// module.exports = {getNotes: getNotes, addNotes: addNotes}  
  
// file 2  
import { name, utilslog } from './utils.js'  
1
module.exports.age = 25;  
1
2
3
module.exports.addNote = () => {  
    console.log('addNote');  
}  

# Importing npm Modules

# Initializing npm

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
{  
	"name": "notes-app",  
	"version": "1.0.0",  
	"description": "",  
	"main": "app.js",  
	"scripts": {  
	"test": "echo \"Error: no test specified\" && exit 1"  
	},  
	"author": "",  
	"license": "ISC",  
}  

# Installing an npm Module

1
2
3
4
# installs version 10.8.0 of validator  
npm install [email protected]  
# installs the latest version  
npm install validator  
1
2
# install as a dev dependency only  
npm install <package-name> --save-dev  

# Importing an npm Module

1
2
3
const validator = require('validator')  
console.log(validator.isURL('https/mead.io')) // true  
console.log(validator.isEmail('gmail.com')) // false  

# Global npm Modules

1
2
# install as a global utility - doesn't add to the project specific package.json  
npm install <package-name> --global   

# What is the difference between .js and .mjs files?

1
2
3
4
5
6
// package.json  
{  
  // assume .js is using...  
  "type": "commonjs", // require/module.exports  
  "type": "module" // import/export  
}