Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

Sorry, you do not have permission to ask a question, You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please type your username.

Please type your E-Mail.

Please choose an appropriate title for the post.

Please choose the appropriate section so your post can be easily searched.

Please choose suitable Keywords Ex: post, video.

Browse

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Logo

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Navigation

  • Home
  • About Us
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • About Us
  • Contact Us
Home/ Questions/Q 8411

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise Latest Questions

Author
  • 60k
Author
Asked: November 28, 20242024-11-28T12:51:08+00:00 2024-11-28T12:51:08+00:00

#2 NodeJS – What is fs module

  • 60k

Image description

Summary

  1. NodeJS has fs module that helps in managing files

  2. 'fs' module has Promise API, Callback API, and Synchronous API.

  3. There are various methods in fs from creating, to deleting the files.

  4. Always use Async methods over sync for improving performance unless and until you have requirements to use sync methods.


Welcome back to my 2nd blog from the series of NodeJS. If you haven't checked my 1st blog, please check here.

Today we will explore the 2nd module (in-built package) of NodeJS – fs (file system).

We have 3 ways to use fs module in NodeJS:

  1. Promise API

  2. callback API

  3. Synchronous API

import mode return
Promise node:fs/promises promise based (async) promise
Callback fs async error/success or data
Synchronous fs sync error/success or data

In this tutorial we will go through the Callback.

What is fs?

NodeJS has native or built-in package fs. FS stands for filesystem. FS enables devs to create, open, read and write files.

This is an important feature. Developers can do a lot by using FS. Developers will have control over the files.

Where to Use?

  1. fs in configurations.

  2. Build Scripts

  3. Temporary data storage

  4. Processing of data before storing in database

How to create a file?

Image description

There are 3 ways (methods) to create a new file:

  1. open: open an existing file.

  2. writeFile: it will create a file if it's not exist and write content in it.

  3. appendFile: it will create a file if it's not exist and append content in it.

How to write content in a file?

  1. writeFile
  • file name

  • data

  • options: encoding, mode, flag

  • callback: error or success

// Example: Callback API const fs = require('fs');  fs.writeFile('logs.txt','hello', 'utf8' (err) => {     if(err) {       console.log('error')      }     else{       console.log('data saved')      } });  // Example: Promise API  import { writeFile } from 'node:fs/promises';  (async function main() {     try {         await writeFile(                 "logs.txt",'hello')          console.log("The written file has"             + " the following contents:");      } catch (err) {         console.error(err);     } })();  
Enter fullscreen mode Exit fullscreen mode

2 . open

  • file name

  • mode

  • callback: error or success

const fs = require('fs');  // Callback API fs.open('logs.txt', 'w', (err) => {     if(err) {       console.log('error')      }     else{       console.log('file open')      } });  // Promise API import { open } from 'node:fs/promises';  (async function main() {     try {         await open(                 "logs.txt")          console.log("The file has been open");      } catch (err) {         console.error(err);     } })(); 
Enter fullscreen mode Exit fullscreen mode

3 . appendFile

  • file name

  • data

  • options: encoding, mode, flag

  • callback: error or success

// callback API fs.appendFile('logs.txt', 'new text', 'utf8' , (err) => {     if(err) {       console.log('error')      }     else{       console.log('data added')      } });  // Promise API import { appendFile } from 'node:fs/promises';  (async function main() {     try {         await appendFile("logs.txt", 'hello');         console.log("The file has been open");      } catch (err) {         console.error(err);     } })(); 
Enter fullscreen mode Exit fullscreen mode

How to read content from a file?

So far we saw how to create and write content to a file. We can also read the file's content.

read

  • file name

  • encoding options: utf8, utf16, base ,etc.

  • callback: error or data

fs.readFile('logs.txt', (err,data) => {     if(err) {       console.log('error')      }     else{       console.log(data); // this will return buffer       console.log(data.toString()); // convert the buffer to string      } }); 
Enter fullscreen mode Exit fullscreen mode

Code:

// import package  const fs = require('fs')  // read a file  const readfile = fs.readFile('logs.txt', 'utf-8'); console.log(readfile);  // write content of a file  const writefile = fs.writeFile('logs.txt', 'hello'); const readfile = writefile.readFile(writefile) console.log(readfile);  // append content  const readfile = fs.appendFile('logs.txt', 'utf-8'); console.log(readfile);  // rename  const logs = fs.createFile('logs.txt');  fs.rename('logs.txt', 'userlogs.txt', () => {     console.log('done') });  // delete  const logs = fs.createFile('logs.txt');  fs.unlink('logs.txt', () => {     console.log('deleted') });  
Enter fullscreen mode Exit fullscreen mode

Code

Important

  1. Content in the file would be either string, buffer, or text. Not, object

  2. writeFile will overwrite the content. Hence, use appendFile

sync vs async

You will see that there are 2 methods in fs: readfile and readFileSync. readFile is async operation. It's a blocking operation and will impact the performance. Hence, prefer to use readFile over readFileSync unless and until you don't have any requirement.

Resources

NodeJS Documentation

Like it? Do follow me on Twitter and Linkedin.

nodeprogrammingtutorialwebdev
  • 0 0 Answers
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

Sidebar

Ask A Question

Stats

  • Questions 4k
  • Answers 0
  • Best Answers 0
  • Users 1k
  • Popular
  • Answers
  • Author

    How to ensure that all the routes on my Symfony ...

    • 0 Answers
  • Author

    Insights into Forms in Flask

    • 0 Answers
  • Author

    Kick Start Your Next Project With Holo Theme

    • 0 Answers

Top Members

Samantha Carter

Samantha Carter

  • 0 Questions
  • 20 Points
Begginer
Ella Lewis

Ella Lewis

  • 0 Questions
  • 20 Points
Begginer
Isaac Anderson

Isaac Anderson

  • 0 Questions
  • 20 Points
Begginer

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help

Footer

Querify Question Shop: Explore Expert Solutions and Unique Q&A Merchandise

Querify Question Shop: Explore, ask, and connect. Join our vibrant Q&A community today!

About Us

  • About Us
  • Contact Us
  • All Users

Legal Stuff

  • Terms of Use
  • Privacy Policy
  • Cookie Policy

Help

  • Knowledge Base
  • Support

Follow

© 2022 Querify Question. All Rights Reserved

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.