WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Node js File System Module Example Tutorial


Node js File System Module Example Tutorial is today‚Äôs leading topic.   The Node.js file system module allows you to work with a file system on your computer. We can include the File System module by using the require() method. The fs module provides the API for interacting with a file system in a manner closely modeled around standard POSIX functions. All node.js file system operations have synchronous and asynchronous forms. The asynchronous form always takes the completion callback as its last argument. The arguments passed to a completion callback depend on a method, but the first argument is always reserved for the exception. If the operation was accomplished successfully, then the first argument will be null or undefined.

Node js File System Module Example Tutorial

The everyday use for the File System module is as follows.

  • Read files
  • Create files
  • Update files
  • Delete files
  • Rename files

#Node.js as a File Server

We can require the fs module like the following code
const fs = require('fs');
Let us take the example of simple file system operation in which we remove the file from disk. Create one folder called filesystem and get inside that folder. Now, create one file called acme.js inside the root for just demo purpose. touch acme.js We will delete this file using the fs module. So type the following code inside the server.js file. // server.js const fs = require('fs'); fs.unlink('acme.js', (err) => { if (err) throw err; console.log('File system operation successfully executed'); }); Now, run the following command in your terminal. node server.js It will give you the output like this and your file will be deleted from the project. . Node js File System Module Example Tutorial

#Using try-catch block

You can wrap the above operation in the try-catch block. Let us say we have already deleted the file and again we try to run the command then we will get the following error.

So, we need to define the try-catch error mechanism. Also for that, we need to perform the sync operation and not async operation. // server.js const fs = require('fs'); try { fs.unlinkSync('acme.js'); console.log('File system operation successfully executed'); } catch(e) { console.log('Excecuted Catch block'); console.log(e); } node-filesystem-example  Tutorial

#File paths,

Most fs operations accept file paths that may be specified in the form of a string, a Buffer, or a URL object using the file protocol. String form paths are interpreted as UTF-8 character sequences identifying the absolute or relative filename. Relative paths will be resolved relative to the current working directory as specified by the process.cwd(). Recreate the acme.js file inside the root. Write the following code inside the server file. // server.js const fs = require('fs'); fs.open('acme.js', 'r', (err, fd) => { if (err) throw err; console.log('File has opened'); fs.close(fd, (err) => { console.log('File is closing'); if (err) throw err; }); });

#URL object support in node fs module

// server.js const fs = require('fs'); const fileUrl = new URL('file:///acme.js'); fs.readFileSync(fileUrl);

#Open a File using Node fs module

The syntax is following to open a file using node fs module. fs.open(path, flags[, mode], callback)

#Get File Information

Following is the syntax of the method to get the information about a particular file. fs.stat(path, callback) Let us take an example of node file stat. // server.js const fs = require('fs'); fs.stat('acme.js', function (err, stats) { if (err) { return console.error(err); } console.log(stats); console.log("Got file info successfully!"); // Check file type console.log("isFile ? " + stats.isFile()); console.log("isDirectory ? " + stats.isDirectory()); }); Run and see the output in the terminal.

#Writing a File using Node fs module.

The syntax is following to write a file in node.js. fs.writeFile(filename, data[, options], callback) This method will overwrite the file if a file already exists. If you want to write into an existing file, then you should use another available method. // server.js const fs = require('fs'); fs.writeFile('acme.js', 'console.log("hello")', function (err) { if (err) throw err; console.log('New file acme.js is either created or if exists then updated'); });

#Reading a file using node fs module.

To read a file in node.js, you can use the following syntax. fs.read(fd, buffer, offset, length, position, callback) Let us take an example and understand how we can read the file using the node fs. // server.js const http = require('http'); const fs = require('fs'); http.createServer(function (req, res) { fs.readFile('acme.js', function(err, data) { res.writeHead(200, {'Content-Type': 'text/js'}); res.write(data); res.end(); }); }).listen(8080);

#Rename Files.

To rename a file with the File System module, use the fs.rename() method. The fs.rename() method renames the specified file. // server.js const fs = require('fs'); fs.rename('acme.js', 'paradox.js', function (err) { if (err) throw err; console.log('File Renamed!'); });

#Delete Files

To delete a file with the File System module, use the fs.unlink() method. The fs.unlink() method deletes the specified file. // server.js const fs = require('fs'); fs.unlink('paradox.js', function (err) { if (err) throw err; console.log('File deleted!'); });