{"id":88,"date":"2019-09-24T07:18:12","date_gmt":"2019-09-24T07:18:12","guid":{"rendered":"https:\/\/www.kindsonthegenius.com\/nodejs\/?p=88"},"modified":"2020-08-06T09:56:47","modified_gmt":"2020-08-06T09:56:47","slug":"node-js-file-system","status":"publish","type":"post","link":"https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/","title":{"rendered":"Node.js &#8211; File System"},"content":{"rendered":"<p>In previous Tutorials, we discussed <a href=\"https:\/\/www.kindsonthegenius.com\/nodejs\/working-with-buffers\/\">Buffers<\/a>, then <a href=\"https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-streams\" target=\"_blank\" rel=\"noopener noreferrer\">Streams<\/a>. File system is related as well.<\/p>\n<p>File System allows you to read and write data to file in your OS. This is made possible by the Node File System module(fs).<\/p>\n<p>We would examine the following sub-topics:<\/p>\n<ol>\n<li><a href=\"#t1\">Asynchronous vs Synchronous Operation<\/a><\/li>\n<li><a href=\"#t2\">Opening a File<\/a><\/li>\n<li><a href=\"#t3\">Getting File Information<\/a><\/li>\n<li><a href=\"#t4\">Writing to a File<\/a><\/li>\n<li><a href=\"#t5\">Reading a File<\/a><\/li>\n<li><a href=\"#t6\">Closing a File<\/a><\/li>\n<li><a href=\"#t7\">Truncating a File<\/a><\/li>\n<li><a href=\"#t8\">Deleting a File<\/a><\/li>\n<li><a href=\"#t9\">Creating a Directory<\/a><\/li>\n<\/ol>\n<p>&nbsp;<\/p>\n<p><strong id=\"t1\">1. Synchronous vs Asynchronous Operations<\/strong><\/p>\n<p>the fs module provides methods that both synchronous and asynchronous forms.<\/p>\n<p>For example, we learnt of readFile() and readFileSync() when we learn of <a href=\"https:\/\/www.kindsonthegenius.com\/nodejs\/06-node-js-introduction-to-callback\/\" target=\"_blank\" rel=\"noopener noreferrer\">callbacks<\/a>. The readFile() is the asynchronous equivalent of readFileSync().<\/p>\n<p>Asynchronous methods take callback functions as the last parameter. There are many benefits of using asynchronous method. It provides for better performance since it does not tie down the thread.<\/p>\n<p>The code below reads data asynchronously from a file named testoutput.txt.<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #888888;\">\/\/Demonstrating Async and Sync operations<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">var<\/span> fs <span style=\"color: #333333;\">=<\/span> require(<span style=\"background-color: #fff0f0;\">\"fs\"<\/span>);\r\n\r\n<span style=\"color: #888888;\">\/\/Read file Asynchronously<\/span>\r\nfs.readFile(<span style=\"background-color: #fff0f0;\">'D:\/nodefiles\/testinput.txt'<\/span>, <span style=\"color: #008800; font-weight: bold;\">function<\/span> (err, data) {\r\n   <span style=\"color: #008800; font-weight: bold;\">if<\/span> (err) {\r\n      <span style=\"color: #008800; font-weight: bold;\">return<\/span> console.error(err);\r\n   }\r\n   console.log(<span style=\"background-color: #fff0f0;\">\"Reading Asynchronously: \"<\/span> <span style=\"color: #333333;\">+<\/span> data.toString());\r\n});\r\n\r\n<span style=\"color: #888888;\">\/\/Reading Synchronously<\/span>\r\n<span style=\"color: #008800; font-weight: bold;\">var<\/span> data <span style=\"color: #333333;\">=<\/span> fs.readFileSync(<span style=\"background-color: #fff0f0;\">'D:\/nodefiles\/testinput.txt'<\/span>);\r\nconsole.log(<span style=\"background-color: #fff0f0;\">\"Reading Synchronously: \"<\/span> <span style=\"color: #333333;\">+<\/span> data.toString());\r\n\r\nconsole.log(<span style=\"background-color: #fff0f0;\">\"End of Program\"<\/span>);\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p><strong id=\"t2\">2. Opening a File<\/strong><\/p>\n<p>You can open a file in your computer using the syntax below.<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">fs.open(path, flags[, mode], callback)\r\n<\/pre>\n<p>Where<\/p>\n<ul class=\"list\">\n<li><b>path<\/b>\u00a0\u2212 is the string having file name including path.<\/li>\n<li><b>flags<\/b>\u00a0\u2212 Flags indicate the behavior of the file to be opened. All possible values have been mentioned in the table below.<\/li>\n<li><b>mode<\/b>\u00a0\u2212 sets the file mode (permission and sticky bits). But only if the file was created. The defaults are 0666, readable and writeable.<\/li>\n<li><b>callback<\/b>\u00a0\u2212 is the callback function to call after a successful operation. It gets two arguments (err, fd).<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p>The flags parameter can be any of the following:<\/p>\n<table class=\"table table-bordered\">\n<tbody>\n<tr>\n<th>SN.<\/th>\n<th>Flag and brief description<\/th>\n<\/tr>\n<tr>\n<td class=\"ts\">1<\/td>\n<td><b>r<\/b><\/p>\n<p>Opens the file for reading. An exception occurs if the file does not exist.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">2<\/td>\n<td><b>r+<\/b><\/p>\n<p>Opens the file for reading and writing. An exception occurs if the file does not exist in the directory.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">3<\/td>\n<td><b>rs<\/b><\/p>\n<p>Opens the file for reading in synchronous mode.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">4<\/td>\n<td><b>rs+<\/b><\/p>\n<p>Opens the file for reading and writing, asking the OS to open it synchronously. To be used\u00a0 with caution.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">5<\/td>\n<td><b>w<\/b><\/p>\n<p>Opens the file for writing. The file is created (if it does not exist). Otherwise it is truncated (if it exists).<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">6<\/td>\n<td><b>wx<\/b><\/p>\n<p>Like &#8216;w&#8217; but fails if the path exists.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">7<\/td>\n<td><b>w+<\/b><\/p>\n<p>Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">8<\/td>\n<td><b>wx+<\/b><\/p>\n<p>Like &#8216;w+&#8217; but fails if path already exists.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">9<\/td>\n<td><b>a<\/b><\/p>\n<p>Opens the file for appending. The file is created if it does not already exist.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">10<\/td>\n<td><b>ax<\/b><\/p>\n<p>Like &#8216;a&#8217; but fails if the path exists.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">11<\/td>\n<td><b>a+<\/b><\/p>\n<p>Opens the file for reading and appending. The file is created if it does not already exist.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">12<\/td>\n<td><b>ax+<\/b><\/p>\n<p>Like &#8216;a+&#8217; but fails if the the path already exists.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>The code below opens a file for reading and writing the flag is r+<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008800; font-weight: bold;\">var<\/span> fs <span style=\"color: #333333;\">=<\/span> require(<span style=\"background-color: #fff0f0;\">\"fs\"<\/span>);\r\n\r\n<span style=\"color: #888888;\">\/\/  Opening a File Asynchronous<\/span>\r\nconsole.log(<span style=\"background-color: #fff0f0;\">\"Opening a file...\"<\/span>);\r\nfs.open(<span style=\"background-color: #fff0f0;\">'D:\/nodefiles\/testinput.txt'<\/span>, <span style=\"background-color: #fff0f0;\">'r+'<\/span>, <span style=\"color: #008800; font-weight: bold;\">function<\/span>(err, fd) {\r\n   <span style=\"color: #008800; font-weight: bold;\">if<\/span> (err) {\r\n      <span style=\"color: #008800; font-weight: bold;\">return<\/span> console.error(err);\r\n   }\r\n   console.log(<span style=\"background-color: #fff0f0;\">\"File was  opened successfully!\"<\/span>);     \r\n});\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p><strong id=\"t3\">3. Getting File Information<\/strong><\/p>\n<p>Node.js allows you to retrieve the properties of a file in your system. This is done using the stat() method of fs object. The syntax is given below:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">fs.stat(path, callback)\r\n<\/pre>\n<p>where<\/p>\n<ul class=\"list\">\n<li><b>path<\/b>\u00a0\u2212 In the path to the file<\/li>\n<li><b>callback<\/b>\u00a0\u2212 is the callback function to execute. It gets two arguments (err, stats) where\u00a0<b>stats<\/b>\u00a0is an object of fs.Stats type.<\/li>\n<\/ul>\n<p>Other methods available in the fs.Stats class in given below. This method is used to get additional metadata of the file<\/p>\n<p>&nbsp;<\/p>\n<table class=\"table table-bordered\">\n<tbody>\n<tr>\n<th>SN.<\/th>\n<th>Method and brief description<\/th>\n<\/tr>\n<tr>\n<td class=\"ts\">1<\/td>\n<td><b>stats.isFile()<\/b><\/p>\n<p>Returns true if file of a simple file type.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">2<\/td>\n<td><b>stats.isDirectory()<\/b><\/p>\n<p>Returns true if the specified path is type of a directory.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">3<\/td>\n<td><b>stats.isBlockDevice()<\/b><\/p>\n<p>Returns true if file type of a block device, otherwise, it returns false.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">4<\/td>\n<td><b>stats.isCharacterDevice()<\/b><\/p>\n<p>Returns true if file type of a character device, otherwise, it returns false.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">5<\/td>\n<td><b>stats.isSymbolicLink()<\/b><\/p>\n<p>Returns true if file type of a symbolic link, otherwise, it returns false.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">6<\/td>\n<td><b>stats.isFIFO()<\/b><\/p>\n<p>Returns true if file type of a FIFO, otherwise, it returns false.<\/td>\n<\/tr>\n<tr>\n<td class=\"ts\">7<\/td>\n<td><b>stats.isSocket()<\/b><\/p>\n<p>Returns true if file type of asocket, otherwise, it returns false.<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Let&#8217;s now apply some of these methods using the code below:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008800; font-weight: bold;\">var<\/span> fs <span style=\"color: #333333;\">=<\/span> require(<span style=\"background-color: #fff0f0;\">\"fs\"<\/span>);\r\n\r\nconsole.log(<span style=\"background-color: #fff0f0;\">\"Getting the file information!\"<\/span>);\r\nfs.stat(<span style=\"background-color: #fff0f0;\">'D:\/nodefiles\/testinput.txt'<\/span>, <span style=\"color: #008800; font-weight: bold;\">function<\/span> (err, stats) {\r\n   <span style=\"color: #008800; font-weight: bold;\">if<\/span> (err) {\r\n      <span style=\"color: #008800; font-weight: bold;\">return<\/span> console.error(err);\r\n   }\r\n   console.log(stats);\r\n   console.log(<span style=\"background-color: #fff0f0;\">\"The file information was retrieved!\"<\/span>);\r\n   \r\n   <span style=\"color: #888888;\">\/\/ Check file type<\/span>\r\n   console.log(<span style=\"background-color: #fff0f0;\">\"isDirectory ? \"<\/span> <span style=\"color: #333333;\">+<\/span> stats.isDirectory());   \r\n   console.log(<span style=\"background-color: #fff0f0;\">\"isFile ? \"<\/span> <span style=\"color: #333333;\">+<\/span> stats.isFile()); \r\n});\r\n<\/pre>\n<p>If you run the code, you will have the output below.(provided the file exists!)<\/p>\n<p>&nbsp;<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">  rdev<span style=\"color: #333333;\">:<\/span> <span style=\"color: #0000dd; font-weight: bold;\">0<\/span>,\r\n  blksize<span style=\"color: #333333;\">:<\/span> <span style=\"color: #008800; font-weight: bold;\">undefined<\/span>,\r\n  ino<span style=\"color: #333333;\">:<\/span> <span style=\"color: #0000dd; font-weight: bold;\">1407374884044874<\/span>,\r\n  size<span style=\"color: #333333;\">:<\/span> <span style=\"color: #0000dd; font-weight: bold;\">62<\/span>,\r\n  blocks<span style=\"color: #333333;\">:<\/span> <span style=\"color: #008800; font-weight: bold;\">undefined<\/span>,\r\n  atimeMs<span style=\"color: #333333;\">:<\/span> <span style=\"color: #6600ee; font-weight: bold;\">1569248643316.3845<\/span>,\r\n  mtimeMs<span style=\"color: #333333;\">:<\/span> <span style=\"color: #6600ee; font-weight: bold;\">1569245334975.0874<\/span>,\r\n  ctimeMs<span style=\"color: #333333;\">:<\/span> <span style=\"color: #6600ee; font-weight: bold;\">1569245334975.0874<\/span>,\r\n  birthtimeMs<span style=\"color: #333333;\">:<\/span> <span style=\"color: #6600ee; font-weight: bold;\">1568998209028.1128<\/span>,\r\n  atime<span style=\"color: #333333;\">:<\/span> <span style=\"color: #0000dd; font-weight: bold;\">2019<\/span><span style=\"color: #333333;\">-<\/span><span style=\"color: #0000dd; font-weight: bold;\">09<\/span><span style=\"color: #333333;\">-<\/span><span style=\"color: #0000dd; font-weight: bold;\">23<\/span>T14<span style=\"color: #333333;\">:<\/span><span style=\"color: #0000dd; font-weight: bold;\">24<\/span><span style=\"color: #333333;\">:<\/span><span style=\"color: #6600ee; font-weight: bold;\">03.316<\/span>Z,\r\n  mtime<span style=\"color: #333333;\">:<\/span> <span style=\"color: #0000dd; font-weight: bold;\">2019<\/span><span style=\"color: #333333;\">-<\/span><span style=\"color: #0000dd; font-weight: bold;\">09<\/span><span style=\"color: #333333;\">-<\/span><span style=\"color: #0000dd; font-weight: bold;\">23<\/span>T13<span style=\"color: #333333;\">:<\/span><span style=\"color: #0000dd; font-weight: bold;\">28<\/span><span style=\"color: #333333;\">:<\/span><span style=\"color: #6600ee; font-weight: bold;\">54.975<\/span>Z,\r\n  ctime<span style=\"color: #333333;\">:<\/span> <span style=\"color: #0000dd; font-weight: bold;\">2019<\/span><span style=\"color: #333333;\">-<\/span><span style=\"color: #0000dd; font-weight: bold;\">09<\/span><span style=\"color: #333333;\">-<\/span><span style=\"color: #0000dd; font-weight: bold;\">23<\/span>T13<span style=\"color: #333333;\">:<\/span><span style=\"color: #0000dd; font-weight: bold;\">28<\/span><span style=\"color: #333333;\">:<\/span><span style=\"color: #6600ee; font-weight: bold;\">54.975<\/span>Z,\r\n  birthtime<span style=\"color: #333333;\">:<\/span> <span style=\"color: #0000dd; font-weight: bold;\">2019<\/span><span style=\"color: #333333;\">-<\/span><span style=\"color: #0000dd; font-weight: bold;\">09<\/span><span style=\"color: #333333;\">-<\/span><span style=\"color: #0000dd; font-weight: bold;\">20<\/span>T16<span style=\"color: #333333;\">:<\/span><span style=\"color: #0000dd; font-weight: bold;\">50<\/span><span style=\"color: #333333;\">:<\/span><span style=\"color: #6600ee; font-weight: bold;\">09.028<\/span>Z }\r\nThe file information was retrieved<span style=\"color: #333333;\">!<\/span>\r\nisDirectory <span style=\"color: #333333;\">?<\/span> <span style=\"color: #008800; font-weight: bold;\">false<\/span>\r\nisFile <span style=\"color: #333333;\">?<\/span> <span style=\"color: #008800; font-weight: bold;\">true<\/span>\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p><strong id=\"t4\">4. Writing to a File<\/strong><\/p>\n<p>You can write to a file using the syntax below:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">fs.writeFile(filename, data[, options], callback)\r\n<\/pre>\n<p>If the file already exists, then the method will overwrite the file.<\/p>\n<p>The parameters are explained as follows:<\/p>\n<ul class=\"list\">\n<li><b>path<\/b>\u00a0\u2212 is the string having the file path.<\/li>\n<li><b>data<\/b>\u00a0\u2212 is the String or Buffer to be written into the specified file.<\/li>\n<li><b>options<\/b>\u00a0\u2212 The third parameter is an object which will hold {encoding, mode, flag}. By default. encoding is utf8, mode is octal value 0666. and flag is &#8216;w&#8217;<\/li>\n<li><b>callback<\/b>\u00a0\u2212 is the callback function which gets a single parameter err that returns an error in case of any writing error.<\/li>\n<\/ul>\n<p>The code below would read and write into a file:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008800; font-weight: bold;\">var<\/span> fs <span style=\"color: #333333;\">=<\/span> require(<span style=\"background-color: #fff0f0;\">\"fs\"<\/span>);\r\n\r\nconsole.log(<span style=\"background-color: #fff0f0;\">\"This is going to write into an existing file\"<\/span>);\r\nfs.writeFile(<span style=\"background-color: #fff0f0;\">'D:\/nodefiles\/nodefiles\/input.txt'<\/span>, <span style=\"background-color: #fff0f0;\">'The best Tuorials ever!'<\/span>, <span style=\"color: #008800; font-weight: bold;\">function<\/span>(err) {\r\n   <span style=\"color: #008800; font-weight: bold;\">if<\/span> (err) {\r\n      <span style=\"color: #008800; font-weight: bold;\">return<\/span> console.error(err);\r\n   }\r\n   \r\n   console.log(<span style=\"background-color: #fff0f0;\">\"Data was written successfully!\"<\/span>);\r\n   console.log(<span style=\"background-color: #fff0f0;\">\"Now, let's read the data\"<\/span>);\r\n   \r\n   fs.readFile(<span style=\"background-color: #fff0f0;\">'D:\/nodefiles\/testinput.txt'<\/span>, <span style=\"color: #008800; font-weight: bold;\">function<\/span> (err, data) {\r\n      <span style=\"color: #008800; font-weight: bold;\">if<\/span> (err) {\r\n         <span style=\"color: #008800; font-weight: bold;\">return<\/span> console.error(err);\r\n      }\r\n      console.log(<span style=\"background-color: #fff0f0;\">\"Reading asynchronously: \"<\/span> <span style=\"color: #333333;\">+<\/span> data.toString());\r\n   });\r\n});\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p><strong id=\"t5\">5. Reading a File<\/strong><\/p>\n<p>You can also read the content of a file using the syntax below:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">fs.read(fd, buffer, offset, length, position, callback)\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p>This methods uses a file descriptor, fd to read the file. The file descriptor object is returned by the open() method. However, to read the file directly using the filename, then you should use the readFile method.<\/p>\n<p>The parameters to the read() method are:<\/p>\n<ul>\n<li><b>fd<\/b> \u2212 This is the file descriptor returned by fs.open() method<\/li>\n<li><b>buffer<\/b> \u2212 This is the buffer object the data will be written to.<\/li>\n<li><b>offset<\/b> \u2212 This is the offset in the buffer where the writing will start.<\/li>\n<li><b>length<\/b> \u2212 This is an integer that specifies the number of bytes to be read.<\/li>\n<li><b>position<\/b> \u2212 This is an integer that specifies where to begin reading from in the file. If position is null, then data will be read from the current file position.<\/li>\n<li><b>callback<\/b> \u2212 This is the callback function to be called when data is read. It takes three arguments, (err, bytesRead, buffer).<\/li>\n<\/ul>\n<p>The example below demonstrates the <em>read()<\/em> operation:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008800; font-weight: bold;\">var<\/span> fs <span style=\"color: #333333;\">=<\/span> require(<span style=\"background-color: #fff0f0;\">\"fs\"<\/span>);\r\n<span style=\"color: #008800; font-weight: bold;\">var<\/span> mybuffer <span style=\"color: #333333;\">=<\/span> <span style=\"color: #008800; font-weight: bold;\">new<\/span> Buffer.alloc(<span style=\"color: #0000dd; font-weight: bold;\">2048<\/span>);\r\n\r\nconsole.log(<span style=\"background-color: #fff0f0;\">\"Opening an existing file for read-write\"<\/span>);\r\nfs.open(<span style=\"background-color: #fff0f0;\">'D:\/nodefiles\/testinput.txt'<\/span>, <span style=\"background-color: #fff0f0;\">'r+'<\/span>, <span style=\"color: #008800; font-weight: bold;\">function<\/span>(err, fd) {\r\n   <span style=\"color: #008800; font-weight: bold;\">if<\/span> (err) {\r\n      <span style=\"color: #008800; font-weight: bold;\">return<\/span> console.error(err);\r\n   }\r\n   console.log(<span style=\"background-color: #fff0f0;\">\"File was opened successfully\"<\/span>);\r\n\r\n   console.log(<span style=\"background-color: #fff0f0;\">\"Starting file read operation\"<\/span>); \r\n   fs.read(fd, mybuffer, <span style=\"color: #0000dd; font-weight: bold;\">0<\/span>, mybuffer.length, <span style=\"color: #0000dd; font-weight: bold;\">0<\/span>, <span style=\"color: #008800; font-weight: bold;\">function<\/span>(err, bytes){\r\n      <span style=\"color: #008800; font-weight: bold;\">if<\/span> (err){\r\n         console.log(err);\r\n      }\r\n      console.log(bytes <span style=\"color: #333333;\">+<\/span> <span style=\"background-color: #fff0f0;\">\" bytes read\"<\/span>);\r\n      \r\n      <span style=\"color: #888888;\">\/\/ Print only read read bytes using the slice method.<\/span>\r\n      <span style=\"color: #008800; font-weight: bold;\">if<\/span>(bytes <span style=\"color: #333333;\">&gt;<\/span> <span style=\"color: #0000dd; font-weight: bold;\">0<\/span>){\r\n         console.log(mybuffer.slice(<span style=\"color: #0000dd; font-weight: bold;\">0<\/span>, bytes).toString());\r\n      }\r\n   });\r\n});\r\n<\/pre>\n<p>&nbsp;<\/p>\n<p><strong id=\"t6\">6. Closing a File<\/strong><\/p>\n<p>It is generally a good practice close files that were opened before exiting the program. To close a file, you use the close method. This takes two parameters: the file description, and a callback. The syntax is given below:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">fs.close(fd, callback)\r\n<\/pre>\n<p>As an exercise, try to open a file, then close it back.<\/p>\n<p>&nbsp;<\/p>\n<p><strong id=\"t7\">7. Truncating a File<\/strong><\/p>\n<p>To truncate a file simply means to change the length of the file. The amount by which to truncate(in bytes) is given as a parameter to the truncate() function. A callback is provided as well. If the length provided is shorter than the file&#8217;s current length, then the file is truncated to the new length. If the length provided is longer, then the file is padded by appending null bytes.<\/p>\n<p>The syntax for truncate is:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">fs.ftruncate(fd, len, callback)\r\n<\/pre>\n<p>The callback take just one parameter: err, an exception object.<\/p>\n<p>&nbsp;<\/p>\n<p><strong id=\"t8\">8. Deleting a File<\/strong><\/p>\n<p>To delete a file, use the unlink() function. The syntax is given below.<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">fs.unlink(path, callback)\r\n<\/pre>\n<p>The callback take just one parameter: err, an exception object.<\/p>\n<p>&nbsp;<\/p>\n<p><strong id=\"t9\">9. Creating a directory<\/strong><\/p>\n<p>You can create a directory in your file system using the syntax below:<\/p>\n<pre style=\"margin: 0; line-height: 125%;\">fs.mkdir(path[, mode], callback)\r\n<\/pre>\n<p>where:<\/p>\n<ul>\n<li><b>path<\/b> \u2212 This is the directory to be created. The name is including path.<\/li>\n<li><b>mode<\/b> \u2212 This is the directory permission to be set for the new directory. The defaults is 0777.<\/li>\n<li><b>callback<\/b> \u2212 This is the callback function to execute. One argument is provided, which is the possible exception at the completion of the callback.<\/li>\n<\/ul>\n<p>The code below creates a directory called node_dir in drive D:\/nodefiles<\/p>\n<pre style=\"margin: 0; line-height: 125%;\"><span style=\"color: #008800; font-weight: bold;\">var<\/span> fs <span style=\"color: #333333;\">=<\/span> require(<span style=\"background-color: #fff0f0;\">\"fs\"<\/span>);\r\n\r\nconsole.log(<span style=\"background-color: #fff0f0;\">\"Create directory in D:\/nodefiles\/node_dir\"<\/span>);\r\nfs.mkdir(<span style=\"background-color: #fff0f0;\">'D:\/nodefiles\/node_dir'<\/span>,<span style=\"color: #008800; font-weight: bold;\">function<\/span>(err) {\r\n   <span style=\"color: #008800; font-weight: bold;\">if<\/span> (err) {\r\n      <span style=\"color: #008800; font-weight: bold;\">return<\/span> console.error(err);\r\n   }\r\n   console.log(<span style=\"background-color: #fff0f0;\">\"Directory ws created successfully!\"<\/span>);\r\n});\r\n<\/pre>\n<p>If you run the code, you will see that the directory is created as shown in the figure below:<\/p>\n<p><a href=\"https:\/\/kindsonthegenius.com\/nodejs\/wp-content\/uploads\/sites\/5\/2019\/09\/Node.js-directory.jpg\"><img loading=\"lazy\" decoding=\"async\" class=\"wp-image-90 aligncenter\" src=\"https:\/\/kindsonthegenius.com\/nodejs\/wp-content\/uploads\/sites\/5\/2019\/09\/Node.js-directory.jpg\" alt=\"Node.js directory\" width=\"618\" height=\"350\" srcset=\"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-content\/uploads\/sites\/5\/2019\/09\/Node.js-directory.jpg 682w, https:\/\/www.kindsonthegenius.com\/nodejs\/wp-content\/uploads\/sites\/5\/2019\/09\/Node.js-directory-300x170.jpg 300w\" sizes=\"auto, (max-width: 618px) 100vw, 618px\" \/><\/a><\/p>\n","protected":false},"excerpt":{"rendered":"<p>In previous Tutorials, we discussed Buffers, then Streams. File system is related as well. File System allows you to read and write data to file &hellip; <\/p>\n","protected":false},"author":1,"featured_media":91,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-88","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-uncategorized"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v27.5 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Node.js - File System - Node.js Tutorials<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Node.js - File System - Node.js Tutorials\" \/>\n<meta property=\"og:description\" content=\"In previous Tutorials, we discussed Buffers, then Streams. File system is related as well. File System allows you to read and write data to file &hellip;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/\" \/>\n<meta property=\"og:site_name\" content=\"Node.js Tutorials\" \/>\n<meta property=\"article:published_time\" content=\"2019-09-24T07:18:12+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2020-08-06T09:56:47+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-content\/uploads\/sites\/5\/2019\/09\/Node.js-File-System.jpg\" \/>\n\t<meta property=\"og:image:width\" content=\"879\" \/>\n\t<meta property=\"og:image:height\" content=\"369\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/jpeg\" \/>\n<meta name=\"author\" content=\"kindsonthegenius\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"kindsonthegenius\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"8 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/node-js-file-system\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/node-js-file-system\\\/\"},\"author\":{\"name\":\"kindsonthegenius\",\"@id\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/#\\\/schema\\\/person\\\/7f8fc5792578d2ff54003fcebe6c46b5\"},\"headline\":\"Node.js &#8211; File System\",\"datePublished\":\"2019-09-24T07:18:12+00:00\",\"dateModified\":\"2020-08-06T09:56:47+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/node-js-file-system\\\/\"},\"wordCount\":1221,\"commentCount\":0,\"image\":{\"@id\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/node-js-file-system\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/wp-content\\\/uploads\\\/sites\\\/5\\\/2019\\\/09\\\/Node.js-File-System.jpg\",\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/node-js-file-system\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/node-js-file-system\\\/\",\"url\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/node-js-file-system\\\/\",\"name\":\"Node.js - File System - Node.js Tutorials\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/node-js-file-system\\\/#primaryimage\"},\"image\":{\"@id\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/node-js-file-system\\\/#primaryimage\"},\"thumbnailUrl\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/wp-content\\\/uploads\\\/sites\\\/5\\\/2019\\\/09\\\/Node.js-File-System.jpg\",\"datePublished\":\"2019-09-24T07:18:12+00:00\",\"dateModified\":\"2020-08-06T09:56:47+00:00\",\"author\":{\"@id\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/#\\\/schema\\\/person\\\/7f8fc5792578d2ff54003fcebe6c46b5\"},\"breadcrumb\":{\"@id\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/node-js-file-system\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/node-js-file-system\\\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/node-js-file-system\\\/#primaryimage\",\"url\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/wp-content\\\/uploads\\\/sites\\\/5\\\/2019\\\/09\\\/Node.js-File-System.jpg\",\"contentUrl\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/wp-content\\\/uploads\\\/sites\\\/5\\\/2019\\\/09\\\/Node.js-File-System.jpg\",\"width\":879,\"height\":369,\"caption\":\"Node.js File System\"},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/node-js-file-system\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Node.js &#8211; File System\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/#website\",\"url\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/\",\"name\":\"Node.js Tutorials\",\"description\":\"Best Node.js Tutorials\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/#\\\/schema\\\/person\\\/7f8fc5792578d2ff54003fcebe6c46b5\",\"name\":\"kindsonthegenius\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/b9d710de456c3d85e5614c3a6992fa3d527425e2ab32b8bd5d85bfbaa235004b?s=96&d=mm&r=g\",\"url\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/b9d710de456c3d85e5614c3a6992fa3d527425e2ab32b8bd5d85bfbaa235004b?s=96&d=mm&r=g\",\"contentUrl\":\"https:\\\/\\\/secure.gravatar.com\\\/avatar\\\/b9d710de456c3d85e5614c3a6992fa3d527425e2ab32b8bd5d85bfbaa235004b?s=96&d=mm&r=g\",\"caption\":\"kindsonthegenius\"},\"url\":\"https:\\\/\\\/www.kindsonthegenius.com\\\/nodejs\\\/author\\\/kindsonthegenius-3\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Node.js - File System - Node.js Tutorials","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/","og_locale":"en_US","og_type":"article","og_title":"Node.js - File System - Node.js Tutorials","og_description":"In previous Tutorials, we discussed Buffers, then Streams. File system is related as well. File System allows you to read and write data to file &hellip;","og_url":"https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/","og_site_name":"Node.js Tutorials","article_published_time":"2019-09-24T07:18:12+00:00","article_modified_time":"2020-08-06T09:56:47+00:00","og_image":[{"width":879,"height":369,"url":"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-content\/uploads\/sites\/5\/2019\/09\/Node.js-File-System.jpg","type":"image\/jpeg"}],"author":"kindsonthegenius","twitter_card":"summary_large_image","twitter_misc":{"Written by":"kindsonthegenius","Est. reading time":"8 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/#article","isPartOf":{"@id":"https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/"},"author":{"name":"kindsonthegenius","@id":"https:\/\/www.kindsonthegenius.com\/nodejs\/#\/schema\/person\/7f8fc5792578d2ff54003fcebe6c46b5"},"headline":"Node.js &#8211; File System","datePublished":"2019-09-24T07:18:12+00:00","dateModified":"2020-08-06T09:56:47+00:00","mainEntityOfPage":{"@id":"https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/"},"wordCount":1221,"commentCount":0,"image":{"@id":"https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/#primaryimage"},"thumbnailUrl":"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-content\/uploads\/sites\/5\/2019\/09\/Node.js-File-System.jpg","inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/","url":"https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/","name":"Node.js - File System - Node.js Tutorials","isPartOf":{"@id":"https:\/\/www.kindsonthegenius.com\/nodejs\/#website"},"primaryImageOfPage":{"@id":"https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/#primaryimage"},"image":{"@id":"https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/#primaryimage"},"thumbnailUrl":"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-content\/uploads\/sites\/5\/2019\/09\/Node.js-File-System.jpg","datePublished":"2019-09-24T07:18:12+00:00","dateModified":"2020-08-06T09:56:47+00:00","author":{"@id":"https:\/\/www.kindsonthegenius.com\/nodejs\/#\/schema\/person\/7f8fc5792578d2ff54003fcebe6c46b5"},"breadcrumb":{"@id":"https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/#primaryimage","url":"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-content\/uploads\/sites\/5\/2019\/09\/Node.js-File-System.jpg","contentUrl":"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-content\/uploads\/sites\/5\/2019\/09\/Node.js-File-System.jpg","width":879,"height":369,"caption":"Node.js File System"},{"@type":"BreadcrumbList","@id":"https:\/\/www.kindsonthegenius.com\/nodejs\/node-js-file-system\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/www.kindsonthegenius.com\/nodejs\/"},{"@type":"ListItem","position":2,"name":"Node.js &#8211; File System"}]},{"@type":"WebSite","@id":"https:\/\/www.kindsonthegenius.com\/nodejs\/#website","url":"https:\/\/www.kindsonthegenius.com\/nodejs\/","name":"Node.js Tutorials","description":"Best Node.js Tutorials","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/www.kindsonthegenius.com\/nodejs\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/www.kindsonthegenius.com\/nodejs\/#\/schema\/person\/7f8fc5792578d2ff54003fcebe6c46b5","name":"kindsonthegenius","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/secure.gravatar.com\/avatar\/b9d710de456c3d85e5614c3a6992fa3d527425e2ab32b8bd5d85bfbaa235004b?s=96&d=mm&r=g","url":"https:\/\/secure.gravatar.com\/avatar\/b9d710de456c3d85e5614c3a6992fa3d527425e2ab32b8bd5d85bfbaa235004b?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/b9d710de456c3d85e5614c3a6992fa3d527425e2ab32b8bd5d85bfbaa235004b?s=96&d=mm&r=g","caption":"kindsonthegenius"},"url":"https:\/\/www.kindsonthegenius.com\/nodejs\/author\/kindsonthegenius-3\/"}]}},"_links":{"self":[{"href":"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/posts\/88","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/comments?post=88"}],"version-history":[{"count":6,"href":"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/posts\/88\/revisions"}],"predecessor-version":[{"id":126,"href":"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/posts\/88\/revisions\/126"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/media\/91"}],"wp:attachment":[{"href":"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/media?parent=88"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/categories?post=88"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.kindsonthegenius.com\/nodejs\/wp-json\/wp\/v2\/tags?post=88"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}