Lesson 283 – Complete 2020 Web Development Bootcamp

Lesson 283 – Understanding Node Module Exports – How to Pass Functions and Data between Files

Your app.js file should not contain code that can be created as separate modules which are then imported into your app.js file.

So the following app.get() should be refactored to create a separate module –

app.get("/", function(req, res) {
	
  let today = new Date();

  let options = {
	weekday: "long",
	day: "numeric",
	month: "long"
  };

  let day = today.toLocaleDateString("en-US", options);
	
	res.render("list", {
		listTitle: day, newListItems: toDoItems
	});

});

The first step is to create a new file (in this case called date.js) in your project directory.

You then cut this code out of the app.get() method and paste it in your date.js file –

let today = new Date();

  let options = {
	weekday: "long",
	day: "numeric",
	month: "long"
  };

  let day = today.toLocaleDateString("en-US", options);

You then wrap that code in a function. In this case, I will call the function “getData”. So the code inside the getData function looks like this –

function getDate() {

let today = new Date();

let options = {
	weekday: "long",
	day: "numeric",
	month: "long"
};

let day = today.toLocaleDateString("en-US", options);

}

You then return the variable day so that the function is returning the value of the day variable. The code with the return included becomes this.

function getDate() {

let today = new Date();

let options = {
	weekday: "long",
	day: "numeric",
	month: "long"
};

let day = today.toLocaleDateString("en-US", options);

return day;

}

In order access the variable day inside the app.js file, you have to link the date.js file to the app.js file by creating a const variable called “data” by inserting this code in the app.js file.

const date = require(__dirname + "/date.js");

This code is inserted at the top of the app.js file beneath the const express and const bodyParser variables like this –

const express = require("express");
const bodyParser = require("body-parser");
const date = require(__dirname + "/date.js");

This code placed in the date.js file, allows you to use the getData function created in the date.js file in any other file –

module.exports = getDate;

To use this function inside the app.get() method, you can create a new variable called let day and assign the date() method to that variable –

app.get("/", function(req, res) {
	
	let day = date();
	res.render("list", {
		listTitle: day, newListItems: toDoItems
	});

});