Index
Example


In this lab, we'll read from a file.

Initialize the project in the normal way
>npm init
Write a text file with content like shown.

Save as file "data/names.txt" (you will need to create sub-directory "data" first).
Asha
Wilma
Riya
Type in the code shown.

Note the callback function.

Save the code as file "read-file.js".

Keywords:

//read-file.js

const
	fs = require('fs'),
	path = 'data/names.txt',
	prn = (obj) => console.log(obj.toString());
	
const callbackFct = (err, fileContents) => {
	if (err) throw err;
	prn('File Contents:');
	prn(fileContents);
}

fs.readFile(path, callbackFct);
Run the program in the normal way.
>node read-file
File Contents:
Asha
Wilma
Riya
Edit the code to use an erroneous filename.

Rerun the app. What happens?
//read-file-with-error.js

const
	fs = require('fs'),
	path = 'data/BAD.txt',
	prn = (obj) => console.log(obj.toString());
	
const callbackFct = (err, fileContents) => {
	if (err) throw err;
	prn('File Contents:');
	prn(fileContents);
}

fs.readFile(path, callbackFct);


References