LAB 1 - creating file using node.js fs module

LAB 1 #opensource

Creating file using node.js fs module:

If we want to work with file system in node, we will need to learn how to create files. In this blog post I will describe how to create and open files in node.js using the "fs" module.

Here are the steps to do it:
  1. var fs = require('fs');
    Include a module to your code.
  2. There are couple of methods to create a file:
  • fs.writeFile("<fileName>",<content>,<callbackFunction>);
    In this case a new file is created with the provided name. 
    After filling the file with content, callback function is called. If a file already exists , the file gets overwritten with a new file.
  • fs.appendFile("<fileName>",<content>,<callbackFunction>);
    This function appends content to the file. 
    After filling the file with content, callback function is called. If the file does not exist, a new file is created with the name and content provided.

Opening a file using node.js fs module:
  • fs.open("<fileName>",<mode>,<callbackFunction>);
    This function opens to the file in the specified mode. If the file does not exist the new file is created with specified name.
List of modes:
table from: https://www.tutorialspoint.com/nodejs/nodejs_file_system.htm
Code examples:

var fs = require('fs'); 


fs.writeFile('lab1.txt''creating the file in node.js'function (err) { 
  if (err
     throw err
  console.log('Success!'); 
}); 

fs.appendFile('lab1.txt''new content'function (err) { 
  if (err
     throw err
  console.log('Success!'); 
}); 

fs.open('lab1.txt''rs'function (errfile) { 
   if (err
     throw err
  console.log('File is opened in "synchronous reading" mode'); 
});



Sources:

https://nodejs.org/api/fs.html
https://www.tutorialspoint.com/nodejs/nodejs_file_system.htm

Comments

Popular posts from this blog

Release 0.3 - PR2

Release 0.4 - PR3

Hacktoberfest Final Blog Post