Index
Example


In this lab, we'll write to a file.

Initialize the project in the normal way
>npm init
Create project sub-directory "out".
out\
Type in the code shown.

Note the callback function.

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

Keywords:

//write-file.js

const
	fs = require('fs'),
	path = 'out/output.txt',
	content = 'line 1\nline 2',
	prn = (o) => console.log(o.toString());
	
const callbackFct = (err) => {
	if (err) throw err;
	prn('File written successfully');
}

fs.writeFile(path, content, callbackFct);
Run the program in the normal way.

The file "out/output.txt" should have two lines of text.
>node write-file


References