Close Menu
Soshace Digital Blog

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    What's Hot
    Recruitment

    Effective Strategies to Overcome International Recruitment Challenges

    Franchising

    Essential Skill of Capabilities Assessment

    Node.js

    Node.js Lesson 12: HTTP Module and Nodemon

    Important Pages:
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Today's Picks:
    • Scaling Success: Monitoring Indexation of Programmatic SEO Content
    • Leveraging Influencers: Key Drivers in New Product Launches
    • How Privacy-First Marketing Will Transform the Industry Landscape
    • The Impact of Social Proof on Thought Leadership Marketing
    • Balancing Value-Driven Content and Promotional Messaging Strategies
    • Top Influencer Marketing Platforms to Explore in 2025
    • Emerging Trends in Marketing Automation and AI Tools for 2023
    • Strategies to Mitigate Duplicate Content in Programmatic SEO
    Wednesday, September 10
    Facebook X (Twitter) Instagram LinkedIn YouTube
    Soshace Digital Blog
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions
    Services
    • SaaS & Tech

      Maximizing Efficiency: How SaaS Lowers IT Infrastructure Costs

      August 27, 2025

      Navigating Tomorrow: Innovations Shaping the Future of SaaS

      August 27, 2025

      Maximizing Impact: Strategies for SaaS & Technology Marketing

      August 27, 2025
    • AI & Automation

      Enhancing Customer Feedback Analysis Through AI Innovations

      August 27, 2025

      Navigating the Impact of AI on SEO and Search Rankings

      August 27, 2025

      5 Automation Hacks Every Home Service Business Needs to Know

      May 3, 2025
    • Finance & Fintech

      Critical Missteps in Finance Marketing: What to Avoid

      August 27, 2025

      Analyzing Future Fintech Marketing Trends: Insights Ahead

      August 27, 2025

      Navigating the Complex Landscape of Finance and Fintech Marketing

      August 27, 2025
    • Legal & Compliance

      Exploring Thought Leadership’s Impact on Legal Marketing

      August 27, 2025

      Maximizing LinkedIn: Strategies for Legal and Compliance Marketing

      August 27, 2025

      Why Transparency Matters in Legal Advertising Practices

      August 27, 2025
    • Medical Marketing

      Enhancing Online Reputation Management in Hospitals: A Guide

      August 27, 2025

      Analyzing Emerging Trends in Health and Medical Marketing

      August 27, 2025

      Exploring Innovative Content Ideas for Wellness Blogs and Clinics

      August 27, 2025
    • E-commerce & Retail

      Strategic Seasonal Campaign Concepts for Online and Retail Markets

      August 27, 2025

      Emerging Trends in E-commerce and Retail Marketing Strategies

      August 27, 2025

      Maximizing Revenue: The Advantages of Affiliate Marketing for E-Commerce

      August 27, 2025
    • Influencer & Community

      Leveraging Influencers: Key Drivers in New Product Launches

      August 27, 2025

      Top Influencer Marketing Platforms to Explore in 2025

      August 27, 2025

      Key Strategies for Successful Influencer Partnership Negotiations

      August 27, 2025
    • Content & Leadership

      The Impact of Social Proof on Thought Leadership Marketing

      August 27, 2025

      Balancing Value-Driven Content and Promotional Messaging Strategies

      August 27, 2025

      Analyzing Storytelling’s Impact on Content Marketing Effectiveness

      August 27, 2025
    • SEO & Analytics

      Scaling Success: Monitoring Indexation of Programmatic SEO Content

      August 27, 2025

      Strategies to Mitigate Duplicate Content in Programmatic SEO

      August 27, 2025

      Effective Data Visualization Techniques for SEO Reporting

      August 27, 2025
    • Marketing Trends

      How Privacy-First Marketing Will Transform the Industry Landscape

      August 27, 2025

      Emerging Trends in Marketing Automation and AI Tools for 2023

      August 27, 2025

      Maximizing ROI: Key Trends in Paid Social Advertising

      August 27, 2025
    Soshace Digital Blog
    Blog / Programming / 18. Node.js Lessons. Work With Files. Fs Module
    Programming

    18. Node.js Lessons. Work With Files. Fs Module

    Ivan RastvorovBy Ivan RastvorovOctober 20, 2016Updated:December 6, 2024No Comments7 Mins Read
    Facebook Twitter Pinterest Telegram LinkedIn Tumblr Email Reddit
    18. Node.js Lessons. Work With Files. Fs Module
    Share
    Facebook Twitter LinkedIn Pinterest Email Copy Link

    new_york_united_states_of_america_night_top_view_hdr_13629_2560x1440

    Dear friends! The key goal of our today’s lesson is to learn how to work with binary data and file system. Node.js contains fs module to work with files, which includes a number of functions for various operations with files and directories.

    If we focus on it more carefully, we will see the first specific feature of this module. Almost all functions have two variants: the first one is simply a function’s name, and the second one is its name with Sync.
    Sync
    means “synchronously.” For example, if I call fs.readFile, this fs.readFile will first read it in its full size, then it will call a callback (fs.readFile(filename,[options], callback) and fs.readFileSync will slow down the process execution by Node.js until the file is read. So, such synchronous call is generally used either in console utilities or when the server is initialized, which is a period, when such brakes are quite acceptable. And an asynchronous call is used in those cases, when we want our event loop to work in its full capacity, which means Node.js doesn’t have to wait when a slow disk starts to work and a file gets read.

    Let us look at a real example of using this principle. Let’s create file read.js. We connect the fs module and call an asynchronous function readFile:

    var fs = require('fs');  
      
    fs.readFile(__filename, function(err, data) {  
      if (err) {  
        console.error(err);  
      } else {  
        console.log(data);  
      }  
    });
    

    This function borrows the file name – in our case, this is a path to the current module file – and receives a callback: the first argument is generally an error, the second one is data and the file content. If it were an asynchronous call, it would look like:

    var fs = require('fs');
      
    var data = fs.readFileSync(__filename);  
    fs.readFile(__filename, function(err, data) {  
      if (err) {  
        console.error(err);  
      } else {  
        console.log(data);  
      }  
    });
    

    Thus, an error would be an exception. But we are going to work only with asynchronous calls further. So, let’s get it started. Pay your attention to the fact that we’ve got not file content within a string, but a specialized buffer object. This buffer object is a highly effective Node.js solution for working with binary data. Technically, buffer is an endless memory area, which is filled here with these data.

    Work with the buffer is similar to work with a string. We can get a zero element here:

    var fs = require('fs');  
      
    fs.readFile(__filename, function(err, data) {  
      if (err) {  
        console.error(err);  
      } else {  
        console.log(data); 
        data[0]
      }  
    });
    

    Or we can get the buffer length:

    var fs = require('fs');  
      
    fs.readFile(__filename, function(err, data) {  
      if (err) {  
        console.error(err);  
      } else {  
        console.log(data); 
        data.length
      }  
    });
    

    But unlike to strings that are totally unchangeable in JavaScript, the buffer content can be changed. To do so, our technical materials include a number of methods starting from the most primitive write, which inserts the string to a buffer changing the former to a binary format considering encoding; and ending with various methods adding full, fractional numbers, those of a double format, etc. considering their computerized binary notation.

    Read More:  Building Rest API With Django Using Django Rest Framework and Django Rest Auth

    In this case, we would like to output the file content as a string, that’s why let us modify the buffer string into the call toString by specifying the coding within the brackets, i.e. the table that explains how to transfer bytes into alphabetic symbols. It is utf-8 by default, so we’ll leave it as it is.

    var fs = require('fs');
    
    fs.readFile(__filename, function(err, data) {
        if (err) {
            console.error(err);
        } else {
            console.log(data.toString());
        }
    });

    Launch it. If I know for sure that I work with strings, I can add coding right here:

    fs.readFile(__filename, {encoding: 'utf-8'} function(err, data) {

    Launch. Everything works. In this case, transformation into a string happens right withing the readFile function.

    And now let us see, what will happen, if there is an error somewhere. For example, I read a file that does not exist:

    var fs = require('fs');
    
    fs.readFile("blablabla", {encoding: 'utf-8'}, function(err, data) {
        if (err) {
            console.error(err);
        } else {
            console.log(data);
        }
    });

    I launch it. So, we see an error inside console.error.

    I draw your attention to the fact that the error includes the following data. First, the error name. In our case, ‘ENOENT’ means the file does not exist. Second, the digital code: error 34. Both codes are fully cross-platform, which means it does not really matter whether I use Windows, Linux or something else. If a file can’t be found, it is always ‘ENOENT’. So, let us test it: if the code is ENOENT, it will react in one way, but if it isn’t – the reaction will be different:

    var fs = require('fs');
    
    fs.readFile("blablabla", {encoding: 'utf-8'}, function(err, data) {
        if (err) {
            if (err.code == 'ENOENT') {
                console.error(err.message);
            } else {
                console.error(err);
            }
        } else {
            console.log(data);
        }
    });
    

    Launch it. Ok. Everything works.

    If you get interested what other errors exist or you want to get the error code decryption in the future, unfortunately, you won’t find it in Node.js documents. You will be able to find it within a libUV source – in our case, inside uv.h . Here various kinds of errors are stored – for example, ENOENT or EACCES. These codes are contained right here because libUV itself is responsible for input-output operations. It transforms various codes of operational systems into cross-platform values. If we know in advance a file does not exist, we can check whether it really does not exist using a special call. For that purpose, we’ve got fs.exists – this call checks whether there is a special path, but it cannot check out what kind of object it is – a file or a directory. For more precise checks there is fs.stat and other variants of this call, which can be analyzed in details in our technical materials.

    Read More:  JSX vs HTML: Overview + Answers to FAQs

    Generally, simple stat is a right solution. It gets a path and returns an object of a specialized type – fs.Stats – containing details on what is stored there. Here is an example how to use it:

    var fs = require('fs');  
      
    fs.stat(__filename, function(err, stats) {  
      console.log(stats.isFile());  
      console.log(stats);  
    }); 
    

    So, I launch it. Console.log is the first one to show true, since it is a file, while the second displayed full information on what is contained following this path. It partly depends on the operational system, file system, but you will generally see the following characteristics: size, mtime and date of creation ctime.

    And here is an example of creating a new file that will contain a data string followed by its renaming.

    var fs = require('fs');  
      
    fs.writeFile("file.tmp", "data", function(err) {  
      if (err) throw err;  
      
      fs.rename("file.tmp", "new.tmp", function(err) {  
        if (err) throw err;  
      
        fs.unlink("new.tmp", function(err) {  
          if (err) throw err;  
        });  
      });
    

    Once the string is renamed, we delete it. Pay your attention to the fact that we check an error in every callback. It means, once the file is created, we always check whether there is an error and how it can be handled. The simplest way to do it is throw. Next we rename and handle it. Every callback should contain error performance because errors can be in various, even unexpected places. If we miss it, we may have no clue later shy the system doesn’t work and where we can find this error.

    So, we’ve learnt some basic capabilities of the fs module and some examples of how these capabilities can be applied. This module has a lot of methods. We recommend you to find them in our technical materials in order to understand they do exist.

    The lesson code is available here.

    1-new-york-city-skyline-tribute-in-lights-and-lower-manhattan-at-night-nyc-jon-holiday

    The materials for this article were borrowed from the screencast.

    We are looking forward to meeting you on our website blog.soshace.com

    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Ivan Rastvorov
    • Website

    Related Posts

    Mastering REST APIs: Essential Techniques for Programmers

    December 18, 2024

    Crafting Interactive User Interfaces Using JavaScript Techniques

    December 17, 2024

    Effective Strategies for Utilizing Frameworks in Web Development

    December 16, 2024
    Leave A Reply Cancel Reply

    You must be logged in to post a comment.

    Stay In Touch
    • Facebook
    • Twitter
    • Pinterest
    • Instagram
    • YouTube
    • Vimeo
    Don't Miss
    Development November 26, 2024

    Mastering IoT Development: A Strategic Guide for Professionals

    Unlock the potential of the Internet of Things with our strategic guide for professionals. Mastering IoT development requires a blend of technical skills, strategic planning, and a keen understanding of market trends to drive innovation and efficiency in your projects.

    If Trello became too small for you.

    September 30, 2016

    Strategies to Boost B2B Lead Conversion Rates Effectively

    December 17, 2024

    Three Latest Books Every Entrepreneur Should Read | Best Business Books

    May 7, 2019

    Categories

    • AI & Automation
    • Angular
    • ASP.NET
    • AWS
    • B2B Leads
    • Beginners
    • Blogs
    • Business Growth
    • Case Studies
    • Comics
    • Consultation
    • Content & Leadership
    • CSS
    • Development
    • Django
    • E-commerce & Retail
    • Entrepreneurs
    • Entrepreneurship
    • Events
    • Express.js
    • Facebook Ads
    • Finance & Fintech
    • Flask
    • Flutter
    • Franchising
    • Funnel Strategy
    • Git
    • GraphQL
    • Home Services Marketing
    • Influencer & Community
    • Interview
    • Java
    • Java Spring
    • JavaScript
    • Job
    • Laravel
    • Lead Generation
    • Legal & Compliance
    • LinkedIn
    • Machine Learning
    • Marketing Trends
    • Medical Marketing
    • MSP Lead Generation
    • MSP Marketing
    • NestJS
    • Next.js
    • Node.js
    • Node.js Lessons
    • Paid Advertising
    • PHP
    • Podcasts
    • POS Tutorial
    • Programming
    • Programming
    • Python
    • React
    • React Lessons
    • React Native
    • React Native Lessons
    • Recruitment
    • Remote Job
    • SaaS & Tech
    • SEO & Analytics
    • Soshace
    • Startups
    • Swarm Intelligence
    • Tips
    • Trends
    • Vue
    • Wiki
    • WordPress
    Top Posts

    Strategic Partnerships: A Key to Scaling Your Business Effectively

    Entrepreneurship December 4, 2024

    React User Login Authentication using useContext and useReducer.

    JavaScript September 4, 2020

    Exploring Innovative Content Ideas for Wellness Blogs and Clinics

    Medical Marketing August 27, 2025

    Anime.js to MP4 and GIF with Node.js and FFMPEG

    Express.js April 25, 2023

    Subscribe to Updates

    Get The Latest News, Updates, And Amazing Offers

    About Us
    About Us

    Soshace Digital delivers comprehensive web design and development solutions tailored to your business objectives. Your website will be meticulously designed and developed by our team of seasoned professionals, who combine creative expertise with technical excellence to transform your vision into a high-impact, user-centric digital experience that elevates your brand and drives measurable results.

    7901 4th St N, Suite 28690
    Saint Petersburg, FL 33702-4305
    Phone: 1(877)SOSHACE

    Facebook X (Twitter) Instagram Pinterest YouTube LinkedIn
    Our Picks
    Programming

    Guidelines to Writing a Clear Spec [Software Specification Document]

    Startups

    Safeguarding Innovation: A Guide to Startup Intellectual Property

    Beginners

    5 Critical Tips for Designing Your First Website

    Most Popular

    Основные принципы и правила нашей команды

    Wiki

    Style like a pro with CSS variables

    CSS

    What is Mentorship in Web Development | How to Find a Coding Mentor

    Tips
    © 2025 Soshace Digital.
    • Home
    • About
    • Services
    • Contact Us
    • Privacy Policy
    • Terms & Conditions

    Type above and press Enter to search. Press Esc to cancel.