// Import a custom File module
const variable = require("filePath");
// Import a Built-in Module
const variable = require("fileName");
// Export the Function
module.exports = functionName;
// Export multiple things as a object
module.exports = {functionName1, functionName2};
// Export a key-value pair by module.exports object
module.exports.key = value;
// File automatically gets wrapped by this function when exported
function(exports, require, module, __filename, __dirname) {
// Statements
}
// ES6 syntax will be used if file extension is .mjs
export function functionName1() {
// Statements
}
// Add "type": "module" in package.json before use
import {functionName1} from "filePath" ;
// Import functionName2, functionName3 by their name as they are not exported by default
import {functionName2, functionName3} from "filePath";
// Export a Function by default
const functionName1 = () => {
// Statements
}
// Export this functionName1 by default from file1
export default functionName1;
// Import functionName1
import functionName1 from "filePath";
// Import functionName2 as variable
import {functionName2 as variable} from "filePath";
// All function will get Imported as variable
import * as variable from "filePath";
// Can access function like this
variable.functionName
const fs = require('fs')
fs.readFile('file.txt', 'utf-8', (err, data) => {statement})
=> Reads the entire contents of a filevar = fs.readFileSync('file.txt', "utf-8")
=> Reads the entire contents of a file and Returns a Buffer in Synchronousvar.replace("value1", "value2")
=> Replace value1 from var to value2fs.writeFile('file.txt', "data", () => {statement})
=> Write in a file, Create a file if needed, Data can be a String or Bufferfs.writeFileSync("file.txt", data)
=> Write in a file, Create a file if needed, in Synchronousconst http = require('http')
const port = process.env.PORT || 3000
=> Port that the process is getting or Run or port 3000 const server = http.createServer((req,res) => {
url = req.url // Access the URL
res.statusCode = 200 // Response code for URL request
res.setHeader("content-type", "file-type") // Type of content sent by server
res.writeHead(responseCode, {"content-type": "file-type"}) // Combination of status code and set header
res.end(var) // Serve your content
})
server.listen(port, hostname, () => {
console.log()
})
const os = require('os')
os.freemem()
=> Returns the amount of free system memory in bytes as an integeros.homedir()
=> Returns the string path of the current user's home directoryos.platform()
=> Returns a string identifying the operating system platformos.release()
=> Returns the operating system as a stringos.type()
=> Returns the operating system name as returned by uname(3)os.version()
=> Returns a string identifying the kernel versionos.hostname()
=> Returns the host name of the operating system as a stringconst path = require("path")
path.basename(path)
=> Returns the last portion of a pathpath.dirname(path)
=> Returns the directory name of a pathpath.join("paths")
=> Returns string with the complete normalized path containing all the segmentspath.join(__dirname, "..")
=> Getting the directory path one folder above, __dirname gives file pathpath.extname(path)
=> Returns the extension of the pathconst url = require("url")
const myURL = new URL('https://example.org:8000')
=> Out put will be https://example.org:8000/a/b/c?d=e#fgh
myURL.pathname = '/a/b/c'
=> Add a Path namemyURL.search = '?d=e'
=> Add get parametermyURL.hash = '#fgh'
=> Add hash, Used when navigating in a particular section of a pageconsole.log(myURL)
=> Prints complete URL objectconsole.log(myURL.href)
=> Prints href from URL objectconst var = require("events")
class myEvent extends var {}
=> Creating a custom event classmyEvent.on("eventName", () => {statement;})
=> Creating a function for our custom eventmyEvent.emit("eventName")
=> Firing the custom eventconst express = require("express")
const app = express()
=> Object corresponding to HTTPconst port = value
app.get("URL", (req, res) => {
res.send("value") // Display a value
res.status(n) // Set a status code
res.sendFile("folderName") // Send a file from the directory path
res.sendFile(path.join(__dirname, "filePath")) // Send a HTML file
res.json({ "key": value }) // Send a JSON
})
app.get('/URL/:var', (req, res) => {})
=> Send a parameter with URL const router = express.Router();
router.post("URL", (req, res) => {
const var = var1(req.body) // var1 is a schema
var.save(); // Saving in the Mongo Compass connected
statement;
});
module.exports = router;
app.listen(port, () => {
console.log(`App listening at http://localhost:${port}`);
});
app.use(path, callback)
=> Used to mount the specified middleware function at path which is being specifiedapp.use("URL", express.static("folderName"))
=> Serve static fileapp.use("URL", require("folderName"))
=> Serve this folder at given URL, To better organize the folder structureapp.use(express.urlencoded())
=> Used to get encoded data when form is submitted const var = (req, res, next) => {
statement;
next(); // Pass control to the next middleware function
}
app.use(var) // Call the function
app.post("URL", (req, res) => {
req.body.var // Access encoded data from form
})
res.status(n).send("")
=> Send status code with res.sendreq.params.var
=> Access the req URL variable that is passed as parameterconst mongoose = require("mongoose")
=> Import mongooseconst mongoURI = "string"
=> String received for Mongo Compass to connect to Database const connectToMongo = () => {
mongoose.connect(mongoURI, () => {
console.log(""Connected to Mongo Successfully"");
});
};
module.exports = connectToMongo;
const { Schema } = mongoose;
const UserSchema = new Schema({
email: { // Name
type: String, // Data Type
required: true, // Require to Fill
unique: true, // Unique
default: value, // Default Value
}});
module.exports = mongoose.model("user", UserSchema);
mongoose.model("modelName", var)
=> Make a Model from Schema, First parameter is Model name and 2nd is Schemamongoose.connection.once("open", function() {statement})
var = new mongoose.schema({ key: value })
var.methods.speak = function() {statement})
var.save(function (err, var) {statement})
const app = express()
app.set("view engine", "pug")
=> Set the template engineapp.set("views", path.join(__dirname, "views"))
res.render("fileName", var)
=> Like .sendFile but used to serve templatereq.body
=> Access values submitted by form using name attributeconst app = express()
app.engine("handlebars", exphbs())
app.set("view engine", "handlebars")
=> Set the templete engine app.get("URL", (req, res) => {
res.render("home") // To serve home.handlebars file inside views folder
})
res.render("fileName", {var: value})
=> Send variablenvm install vN.N.N
=> Install a particular node versionnvm use vN.N.N
=> Use a particular node versionnpm i -g nodemon
nodemon index.js