Applied Programming/Files/JavaScript
< Applied Programming | Files
files.js
edit/* This program demonstrates synchronous file I/O. It creates a file,
displays the file, appends data to the file, displays the file, and
then deletes the file. It will not run if the file already exists.
Input:
None
Output:
C F
0 32.0
1 33.8
...
References:
https://www.geeksforgeeks.org/node-js-fs-readfile-method/
https://www.geeksforgeeks.org/node-js-fs-writefilesync-method/
https://flaviocopes.com/how-to-remove-file-node/
*/
const fs = require("fs");
if (typeof module != "undefined" && !module.parent) {
main();
}
/**
* Runs the main program logic.
*/
function main()
{
var filename = "~file.txt";
if(fileExists(filename))
{
console.log("File already exists.")
}
else
{
createFile(filename);
readFile(filename);
appendFile(filename);
readFile(filename);
deleteFile(filename);
}
}
/**
* Creates a text file.
*
* @param Text filename to create.
*/
function createFile(filename)
{
let data = "C\tF\n";
for(let celsius = 0; celsius <= 50; celsius++)
{
let fahrenheit = celsius * 9 / 5 + 32;
data += `${celsius}\t${fahrenheit.toFixed(1)}\n`;
}
try {
fs.writeFileSync(filename, data);
} catch (error) {
console.error(error);
}
}
/**
* Reads a text file.
*
* @param Text filename to read.
*/
function readFile(filename)
{
try {
let data = fs.readFileSync(filename, "utf-8");
let lines = data.split("\n");
for(const line of lines) {
console.log(line);
}
} catch (error) {
console.error(error);
}
}
/**
* Append to a text file.
*
* @param Text filename to append to.
*/
function appendFile(filename)
{
let data = "";
for(let celsius = 51; celsius <= 100; celsius++)
{
let fahrenheit = celsius * 9 / 5 + 32;
data += `${celsius}\t${fahrenheit.toFixed(1)}\n`;
}
try {
fs.appendFileSync(filename, data);
} catch (error) {
console.error(error);
}
}
/**
* Deletes a file.
*
* @param Text filename to delete.
*/
function deleteFile(filename)
{
try {
fs.unlinkSync(filename);
} catch (error) {
console.error(error);
}
}
/**
* Checks to see if a file exists.
*
* @param Text filename to check.
* @returns true if exists or false if not.
*/
function fileExists(filename)
{
return fs.existsSync(filename);
}
Try It
editCopy and paste the code above into one of the following free online development environments or use your own JavaScript compiler / interpreter / IDE.