Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • fs module in nodejs

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 479
    Comment on it

    Welcome to FindNerd,

    Today we are going to discuss an example of nodejs modules. We have already discussed the nodejs in-built modules in our previous blog. click here  to check the blog. We are going to take an example of fs module in nodejs.

    Please take a look.

     

    1. // file name control.js
    2.  
    3. var mod_fs = require('fs'); //loaded fs module
    4.  
    5. var mod_stream = mod_fs.createReadStream('nerd.json'); // created read stream for file nerd.json
    6.  
    7. mod_stream.pause(); // pasued the stream
    8.  
    9. console.log('Stream has been paused'); //Message for pasue action
    10.  
    11. setTimeout(function() {
    12.     console.log('Stream resuming now...'); // After three seconds resume the stream
    13.     mod_stream.resume();
    14. }, 3000);
    15.  
    16. mod_stream.on('data', function (material) {
    17.     console.log('----------------started----------------');
    18.     console.log(material.toString()); // get the content
    19.     console.log('----------------ended----------------');
    20. });
    21.  
    22.  
    23. mod_stream.on('data', function (material) {
    24.     console.log('CONTENT LENGTH WAS: ' + material.length); // get the length of file
    25. });
    26.  
    27. mod_stream.on('end', function () {
    28.     console.log('----------------ended----------------'); // End the process
    29. });

     

    1. // nerd.js
    2. {
    3.     "347": {
    4.         "number": 347,
    5.         "origin": "SRE",
    6.         "destination": "UMA",
    7.         "departs": "12:00 AM",
    8.         "arrives": "12:00 PM"
    9.     },
    10.     "734": {
    11.         "number": 734,
    12.         "origin": "DDN",
    13.         "destination": "BRN",
    14.         "departs": "9:00 AM",
    15.         "arrives": "7:30 PM"
    16.     }
    17. }

     

    Output

     

    A) First of all we have loaded the fs module. After that, we have created read stream and we are reading nerd.json file.

     

    B) Then we have paused the stream and showing a message for it. After that, we are resuming stream after 3 minutes.

     

    C) We are getting content and its length using toString and length function inside on event.

     

    D) We have also shown a content of nerd.js file and you can see the screenshot of output as well.


    Thank you for being with us!

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: