VOOZH about

URL: https://en.wikiversity.org/wiki/Applied_Programming/Files/JavaScript

⇱ Applied Programming/Files/JavaScript - Wikiversity


Jump to content
From Wikiversity

files.js

[edit | edit source]
/* 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/
*/

constfs=require("fs");

if(typeofmodule!="undefined"&&!module.parent){
main();
}

/**
 * Runs the main program logic.
 */
functionmain()
{
varfilename="~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.
 */
functioncreateFile(filename)
{
letdata="C\tF\n";
for(letcelsius=0;celsius<=50;celsius++)
{
letfahrenheit=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.
 */
functionreadFile(filename)
{
try{
letdata=fs.readFileSync(filename,"utf-8");
letlines=data.split("\n");
for(constlineoflines){
console.log(line);
}
}catch(error){
console.error(error);
}
}

/**
 * Append to a text file.
 * 
 * @param Text filename to append to.
 */
functionappendFile(filename)
{
letdata="";
for(letcelsius=51;celsius<=100;celsius++)
{
letfahrenheit=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.
 */
functiondeleteFile(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.
 */
functionfileExists(filename)
{
returnfs.existsSync(filename);
}

Try It

[edit | edit source]

Copy and paste the code above into one of the following free online development environments or use your own JavaScript compiler / interpreter / IDE.

See Also

[edit | edit source]