{"id":19454,"date":"2022-09-29T20:05:45","date_gmt":"2022-09-29T14:35:45","guid":{"rendered":"https:\/\/golocalclassified.com\/article\/?p=19454"},"modified":"2022-09-29T20:05:49","modified_gmt":"2022-09-29T14:35:49","slug":"writing-files-in-nodejs-here-is-what-you-need-to-know","status":"publish","type":"post","link":"https:\/\/golocalclassified.com\/article\/writing-files-in-nodejs-here-is-what-you-need-to-know\/","title":{"rendered":"Writing Files In Nodejs? Here Is What You Need To Know."},"content":{"rendered":"<p>NodeJs file system module will allow us to do file operations create, read, write, update, delete, rename. In this blog, we will use the fs module to perform file operations. In the fs module, every method has asynchronous as well as synchronous forms. Asynchronous methods take the first parameter of the callback function as error and the last parameter as the completion function callback. It\u2019s better to go with the asynchronous method instead of the synchronous method.<\/p>\n<h2 class=\"subbuzz__title xs-mb1 bold\"><span class=\"js-subbuzz__title-text\">Now let\u2019s move on to Nodejs file examples<\/span><\/h2>\n<p><strong>Step 1:<\/strong> Create a directory for our application.<\/p>\n<p>$ mkdir nodeFileOperations<\/p>\n<p>$ cd nodeFileOperations<\/p>\n<p><strong>Step 2:<\/strong> Now generate package.json. Run the following command. So that all the dependencies can be listed.<\/p>\n<p>$ npm init<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/img.buzzfeed.com\/buzzfeed-static\/static\/2019-06\/11\/5\/asset\/buzzfeed-prod-web-05\/sub-buzz-1275-1560244682-1.jpg?downsize=700%3A%2A&amp;output-quality=auto&amp;output-format=auto&amp;output-quality=auto&amp;output-format=auto&amp;downsize=360:*\" \/><\/p>\n<div id=\"mod-subbuzz-image-1\" class=\"subbuzz subbuzz-image xs-mb4 xs-relative xs-mb1\" data-module=\"subbuzz-image\">\n<figure class=\"subbuzz__media\">\n<div class=\"flex xs-flex-column\">\n<div class=\"subbuzz__description \">\n<p><strong>Step 3:<\/strong> Install the fs module by the following command<\/p>\n<p>$ npm install fs<\/p>\n<p>After installing the fs module and make your nodejs server run. It will run on port 3000. Please find below code.<\/p>\n<p>const fs = require(&#8216;fs&#8217;);<\/p>\n<p>const bodyParser = require(&#8216;body-parser&#8217;);<\/p>\n<p>const session = require(&#8216;express-session&#8217;);<\/p>\n<p>const cors = require(&#8216;cors&#8217;);<\/p>\n<p>const app = express();<\/p>\n<p>app.use(bodyParser.json());<\/p>\n<p>app.use(session({<\/p>\n<p>secret : &#8216;thesecret&#8217;,<\/p>\n<p>saveUninitialized: false,<\/p>\n<p>resave : false<\/p>\n<p>}));<\/p>\n<p>router = express.Router({<\/p>\n<p>mergeParams: true<\/p>\n<p>}), router.use(cors());<\/p>\n<p>const startServer = async () =&gt; {<\/p>\n<p>const port = process.env.SERVER_PORT || 3000;<\/p>\n<p>await promisify(app.listen).bind(app)(port);<\/p>\n<p>console.log(`Listening on port ${port}`);<\/p>\n<p>}<\/p>\n<p>startServer();<\/p>\n<p>module.exports = router;<\/p>\n<\/div>\n<\/div>\n<\/figure>\n<\/div>\n<div id=\"mod-subbuzz-text-2\" class=\"subbuzz subbuzz-text xs-mb4 xs-relative \" data-module=\"subbuzz-text\">\n<h4><strong>Important flags:<\/strong><\/h4>\n<p>r: Open file for reading, the exception will come when a file does not exist.<\/p>\n<p>r+: Open file for reading and writing, the exception will come when the file does not exist.<\/p>\n<p>rs: Open file for reading in the mode of synchronous.<\/p>\n<p>rs+: Open file for reading and writing, asking the OS to open the file in the mode of synchronous.<\/p>\n<p>w: Open file for writing. The file will create if not exist or truncate if exist.<\/p>\n<p>wx: Open file for writing like \u2018w\u2019 but fails if the path exists.<\/p>\n<p>w+: Open file for reading and writing, the file is created if it does not exist or truncated if exists.<\/p>\n<p>wx+: Open file for read and write like \u2018w+\u2019 but fails if the path exists.<\/p>\n<p>a: Open file for appending, the file will create if it does not exists.<\/p>\n<p>ax: Open file for appending like \u2018a\u2019 but fails if the path exists.<\/p>\n<p>a+: Open file for reading and appending and the file is created if it does not exist.<\/p>\n<p>ax+: Open file for reading and appending like \u2018a+\u2019 but fails if the path exists.<\/p>\n<\/div>\n<div id=\"mod-subbuzz-text-3\" class=\"subbuzz subbuzz-text xs-mb4 xs-relative \" data-module=\"subbuzz-text\">\n<div id=\"122855541\" class=\"subbuzz-anchor\"><\/div>\n<h2 class=\"subbuzz__title xs-mb1 bold\"><span class=\"js-subbuzz__title-text\">Open a file:<\/span><\/h2>\n<p>To open a file in asynchronous mode use below syntax.<\/p>\n<p>fs.open(path, flags[, mode], callback)<\/p>\n<\/div>\n<div id=\"mod-subbuzz-text-4\" class=\"subbuzz subbuzz-text xs-mb4 xs-relative \" data-module=\"subbuzz-text\">\n<h2 class=\"subbuzz__title xs-mb1 bold\"><span class=\"js-subbuzz__title-text\">Parameters:<\/span><\/h2>\n<p>Path: This is a string should have a file name along with the path.<\/p>\n<p>Flags: Flags indicate the behavior of the file to be opened. All possible flags are mentioned above.<\/p>\n<p>Mode: It sets the file mode, but only the file was created, it defaults to readable and writable.<\/p>\n<p>Callback: Its a callback function which gets two arguments.<\/p>\n<p>console.log(&#8220;Going to open file!&#8221;);<\/p>\n<p>fs.open(&#8216;input.txt&#8217;, &#8216;r+&#8217;, (err, fd) =&gt; {<\/p>\n<p>if (err) {<\/p>\n<p>return console.error(err);<\/p>\n<p>}<\/p>\n<p>console.log(&#8220;File opened successfully!..&#8221;);<\/p>\n<p>});<\/p>\n<p>Output:<\/p>\n<p>Going to open file<\/p>\n<p>Listening on port 3000<\/p>\n<p>File opened successfully!\u2026<\/p>\n<\/div>\n<div id=\"mod-subbuzz-text-5\" class=\"subbuzz subbuzz-text xs-mb4 xs-relative \" data-module=\"subbuzz-text\">\n<h2 class=\"subbuzz__title xs-mb1 bold\"><span class=\"js-subbuzz__title-text\">Create Files:<\/span><\/h2>\n<p>To create new files fs module has the following methods:<\/p>\n<p>fs.appendFile()<\/p>\n<p>fs.open()<\/p>\n<p>fs.writeFile()<\/p>\n<p>The fs.appendFile() method appends specific content to the file. If the file does not exist, then the file will create.<\/p>\n<p>const fs = require(&#8216;fs&#8217;);<\/p>\n<p>fs.appendFile(&#8216;input.txt&#8217;, &#8216;Hello content!&#8217;, (err) =&gt; {<\/p>\n<p>if (err) throw err;<\/p>\n<p>console.log(&#8216;Content Saved!..&#8217;);<\/p>\n<p>});<\/p>\n<p>Output:<\/p>\n<p>Listening on port 3000<\/p>\n<p>console.log(\u2018Content Saved!..\u2019);<\/p>\n<p>fs.writeFile() method replaces the specified file and content if it exists. If the file does not exist, a new file containing the given content will be created.<\/p>\n<p>const fs = require(&#8216;fs&#8217;);<\/p>\n<p>fs.writeFile(&#8216;input.txt&#8217;, &#8216;Hello Write file content!&#8217;, (err) =&gt; {<\/p>\n<p>if (err) throw err;<\/p>\n<p>console.log(&#8216;Write file content saved!&#8230;&#8217;);<\/p>\n<p>});<\/p>\n<p>Output:<\/p>\n<p>Listening on port 3000<\/p>\n<p>Write file content saved!\u2026<\/p>\n<\/div>\n<div id=\"mod-subbuzz-text-6\" class=\"subbuzz subbuzz-text xs-mb4 xs-relative \" data-module=\"subbuzz-text\">\n<h2 class=\"subbuzz__title xs-mb1 bold\"><span class=\"js-subbuzz__title-text\">Update Files:<\/span><\/h2>\n<p>The fs module has the following methods for updating.<\/p>\n<p>fs.appendFile(): This method appends the given content at the end of the specified file.<\/p>\n<p>fs.writeFile(): This method replaces the given file and content.<\/p>\n<\/div>\n<div id=\"mod-subbuzz-text-7\" class=\"subbuzz subbuzz-text xs-mb4 xs-relative \" data-module=\"subbuzz-text\">\n<h2 class=\"subbuzz__title xs-mb1 bold\"><span class=\"js-subbuzz__title-text\">Delete Files:<\/span><\/h2>\n<p>fs.unlink() method will use to delete a file by using fs module.<\/p>\n<p>const fs = require(&#8216;fs&#8217;);<\/p>\n<p>fs.unlink(&#8216;input.txt&#8217;, (err) =&gt; {<\/p>\n<p>if (err) throw err;<\/p>\n<p>console.log(&#8216;File deleted!..&#8217;);<\/p>\n<p>});<\/p>\n<p>Output:<\/p>\n<p>Listening on port 3000<\/p>\n<p>File deleted!\u2026<\/p>\n<\/div>\n<div id=\"mod-subbuzz-text-8\" class=\"subbuzz subbuzz-text xs-mb4 xs-relative \" data-module=\"subbuzz-text\">\n<h2 class=\"subbuzz__title xs-mb1 bold\"><span class=\"js-subbuzz__title-text\">Rename Files:<\/span><\/h2>\n<p>fs.rename() method will be used to rename a specified file.<\/p>\n<p>const fs = require(&#8216;fs&#8217;);<\/p>\n<p>fs.rename(&#8216;input.txt&#8217;, &#8216;input_renamed.txt&#8217; (err) =&gt; {<\/p>\n<p>if (err) throw err;<\/p>\n<p>console.log(&#8216;File Renamed!..&#8217;);<\/p>\n<p>});<\/p>\n<\/div>\n<div id=\"mod-subbuzz-text-9\" class=\"subbuzz subbuzz-text xs-mb4 xs-relative \" data-module=\"subbuzz-text\">\n<h2 class=\"subbuzz__title xs-mb1 bold\"><span class=\"js-subbuzz__title-text\">Create a Directory:<\/span><\/h2>\n<p>fs.mkdir() method is used to make a directory:<\/p>\n<p>const fs = require(&#8216;fs&#8217;);<\/p>\n<p>fs.mkdir(&#8216;\/tmp\/home\/test&#8217;, (err) =&gt; {<\/p>\n<p>if (err) throw err;<\/p>\n<p>console.log(&#8220;Directory created successfully!..&#8221;);<\/p>\n<p>});<\/p>\n<p>Output:<\/p>\n<p>Listening port 3000<\/p>\n<p>Directory created successfully!\u2026<\/p>\n<\/div>\n<div id=\"mod-subbuzz-text-10\" class=\"subbuzz subbuzz-text xs-mb4 xs-relative \" data-module=\"subbuzz-text\">\n<h2 class=\"subbuzz__title xs-mb1 bold\"><span class=\"js-subbuzz__title-text\">Read a Directory:<\/span><\/h2>\n<p>fs.readdir() method is used to read a directory.<\/p>\n<p>const fs = require(&#8216;fs&#8217;);<\/p>\n<p>fs.readdir(&#8220;\/tmp\/home\/nodeFileOperations\/&#8221;, (err, files) =&gt; {<\/p>\n<p>if (err) throw err;<\/p>\n<p>files.forEach((file) =&gt; {<\/p>\n<p>console.log(file);<\/p>\n<p>});<\/p>\n<p>});<\/p>\n<p>Output:<\/p>\n<p>Listening on port 3000<\/p>\n<p>index.js<\/p>\n<p>index_1.js<\/p>\n<p>input.txt<\/p>\n<p>node_modules<\/p>\n<p>package-lock.json<\/p>\n<p>Package.json<\/p>\n<\/div>\n<div id=\"mod-subbuzz-text-11\" class=\"subbuzz subbuzz-text xs-mb4 xs-relative \" data-module=\"subbuzz-text\">\n<h2 class=\"subbuzz__title xs-mb1 bold\"><span class=\"js-subbuzz__title-text\">Remove a Directory:<\/span><\/h2>\n<p>fs.rmdir() method is used to remove a directory<\/p>\n<p>const fs = require(&#8216;fs&#8217;);<\/p>\n<p>fs.rmdir(&#8220;\/tmp\/home\/nodeFileOperations\/&#8221;, (err) =&gt; {<\/p>\n<p>if (err) throw err;<\/p>\n<p>console.log(&#8220;Going to read directory \/tmp\/home\/&#8221;);<\/p>\n<p>fs.readdir(&#8220;\/tmp\/home\/&#8221;, (err, files) =&gt; {<\/p>\n<p>if (err) throw err;<\/p>\n<p>files.forEach((file) =&gt; {<\/p>\n<p>console.log(file);<\/p>\n<p>});<\/p>\n<p>});<\/p>\n<p>});<\/p>\n<\/div>\n<div id=\"mod-subbuzz-text-12\" class=\"subbuzz subbuzz-text xs-mb4 xs-relative \" data-module=\"subbuzz-text\">\n<h2 class=\"subbuzz__title xs-mb1 bold\"><span class=\"js-subbuzz__title-text\">Useful methods of fs module:<\/span><\/h2>\n<p>fs.readFile(file_name [,options], callback): This method reads an existing file.<\/p>\n<p>fs.writeFile(file_name, data[, options], callback): This method writes to the file. If a file exists then overwrite the content otherwise it will create a new file.<\/p>\n<p>fs.open(path, flags[, mode], callback): This method open file for reading or writing.<\/p>\n<p>fs.rename(oldPath, newPath, callback): This method will rename an existing file.<\/p>\n<p>fs.chown(path, uid, gid, callback): This will asynchronous chown.<\/p>\n<p>fs.stat(path, callback): This method will return fs.stat object which includes important file statistics.<\/p>\n<p>fs.link(srcpath, dstpath, callback): This method will links a file asynchronously.<\/p>\n<p>fs.symlink(destination, path[, type], callback): This method will do Symlink asynchronously.<\/p>\n<p>fs.rmdir(path, callback): This method will rename an existing directory.<\/p>\n<p>fs.mkdir(path[, mode], callback): This method will create a new directory.<\/p>\n<p>fs.readdir(path, callback): This method will read the content of the specified directory.<\/p>\n<p>fs.utimes(path, atime, mtime, callback): This method changes the timestamp of the file.<\/p>\n<p>fs.exists(path, callback): This method determines whether the specified file exists or not.<\/p>\n<p>fs.access(path[, mode], callback): This method will test a user\u2019s permissions for the specified file.<\/p>\n<p><span style=\"font-weight: 400;\">Mobile apps have become an important part of every business. Mobile apps have been affecting business for quite a while and help in expanding scalability. Developing an astonishing-looking app with robust security and modern technology is a tough task.\u00a0<\/span><\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>NodeJs file system module will allow us to do file operations create, read, write, update, delete, rename. In this blog, we will use the fs module to perform file operations. In the fs module, every method has asynchronous as well as synchronous forms. Asynchronous methods take the first parameter of the callback function as error [&hellip;]<\/p>\n","protected":false},"author":18806,"featured_media":19453,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[4531,4532,4533,4530],"class_list":["post-19454","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-uncategorized","tag-nodejs","tag-nodejs-server","tag-nodejs-tutorial","tag-writing-files-in-nodejs"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/golocalclassified.com\/article\/wp-json\/wp\/v2\/posts\/19454","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/golocalclassified.com\/article\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/golocalclassified.com\/article\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/golocalclassified.com\/article\/wp-json\/wp\/v2\/users\/18806"}],"replies":[{"embeddable":true,"href":"https:\/\/golocalclassified.com\/article\/wp-json\/wp\/v2\/comments?post=19454"}],"version-history":[{"count":0,"href":"https:\/\/golocalclassified.com\/article\/wp-json\/wp\/v2\/posts\/19454\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/golocalclassified.com\/article\/wp-json\/wp\/v2\/media\/19453"}],"wp:attachment":[{"href":"https:\/\/golocalclassified.com\/article\/wp-json\/wp\/v2\/media?parent=19454"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/golocalclassified.com\/article\/wp-json\/wp\/v2\/categories?post=19454"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/golocalclassified.com\/article\/wp-json\/wp\/v2\/tags?post=19454"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}