I had a big drop in self confidence and lost my pace on catching up on to the bootcamp, however, during the past week's pair programming I met this great 2 guys who helped me to understand what callback and promises are and also gave me a motivation to work on my dream to start up a busines in Southeast Asia. However today I am here to get my blog going on again and share some things I learned today.
The sprint was about learning how to use fs.module in node.js. I know this sounds really something new but it is basically a module that allows you to read a file using JS codes. The sprint required me to construct a code that reads a file and then use callbacks, promises, and async/await to return the merged data.
The first challenge was to come up with a function that reads a given file and returns the information in the given file.
const fs = require("fs"); // this lets you use the fs.module it is something like the import command in React.
const getDataFromFile = function (filePath, callback) {
fs.readFile(filePath, 'utf-8', (error, data) => { // this is how you use the fs.module inside your function. The first parameter is the location of the file you want to read on, the second is some kind of code I will have to study on, and the third is a callback function which holds a parameter of error and data.
if (error) callback(error, null);
else callback(null, data)
})
}
Next is using the promise constructor to accomplish the same thing as the above code.
const fs = require("fs");
const getDataFromFilePromise = filePath => {
return new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf-8', (error, data) => {
if (error) reject(error) // When using Promise constructor instead, you don't have to throw an error when the information holds an error, we use reject as a function to throw an error.
else resolve(data) // We then use resolve when the data is given and is not an error.
})
})
};