Nodejs Course

- Get File Information
- Create and Add data in a File
- Rename file
- Delete file
- fs-extra module

The Node.js file system module (fs) allows you to work with files and folders on your server.
Use this code to include the "fs" module:
const fs = require('fs');

Read File

To read a file on your server, you can use the fs.readFile() method.
Example: Assume we have the following HTML file, called "file1.htm" (located in a "test/" folder, in the Node.js directory):
<html>
<body>
<h1>H1 Title Header</h1>
<p>Some text content.</p>
</body>
</html>
Create a Node.js file that reads the HTML file, and return the content:
//include http and fs modules
const http = require('http');
const fs = require('fs');

//path and file name to read
let file ='./test/file1.htm';

//sets server
const server = http.createServer((req, res)=>{
  //reads the file; if no error, output its content
  fs.readFile(file, (err, data)=>{
    if(err) throw err;
    else {
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.write(data);
    }
    res.end();
  });
});

//listens the server on port 8080
server.listen(8080, ()=> {
  console.log('Server running at //localhost:8080/');
});
Save the code above in a file called "readfile1.js", and initiate the file in command line interface. Then, access the server in your browser: "//localhost:8080/".
- In browser will appear a page with the content of the "file1.htm" file.

Get File Information

To get the information about a file, use the fs.stat() method.
Example: Get object with information about "file1.htm":
const fs = require('fs');
var file ='./test/file1.htm';

fs.stat(file, (err, stats)=>{
  if(err) throw err;
   console.log(stats);
   
   // Check file type
   console.log('isFile ? '+ stats.isFile());
});
If you save the code above in a Node.js file, for example called "fileinfo.js" and run the file in command line interface, you'll get a result like in this screenshoot:
node.js File info
- The stats parameter of the callback function is an object with file information (mode, size, etc.); also, it has methods which can be used to check file type.
stats.isFile() - Returns true if file type of a simple file.
stats.isDirectory() - Returns true if file type of a directory.
stats.isBlockDevice() - Returns true if file type of a block device.

Create and Add data in a File

The "fs" module has methods for creating new files, or adding data in existing file: 1. If the specified file exists, the fs.appendFile() method appends specified content to that file. If the file does not exist, the file will be created.
- Example: Create a html file using the appendFile() method:
const fs = require('fs');
var file ='./test/newfile.htm';
var content ='<div>Html content</div>';

fs.appendFile(file, content, (err)=>{
  if(err) throw err;
  console.log('Saved.');
});
If you save the code above in a Node.js file, and initiate it in the command line interface, a new file "newfile.htm" will be created in "test/" folder (located in the same directory as the Node.js application).

2. The fs.open() method takes a "flag" as the second argument, if the flag is "w" for "writing", the specified file is opened for writing. If the file does not exist, an empty file is created.
- The fs.open() method can be used to create, read, write a file, depending on the specified flag (r, r+, a, w, w+, etc.). See fs.open() documentation page.
- Example: Create a html file using the fs.open() method, and add content in the opened file using fs.write() method:
const fs = require('fs');
var file ='./test/newfile.htm';
var content ='<div>Html content</div>';

fs.open(file, 'w', (err, fd)=>{
  if(err) throw err;
  else {
    console.log('File created');
    fs.write(fd, content, (err)=>{
      if(err) throw err;
      console.log('Data added in file');
      fs.close(fd, (err)=>{ if(err) throw err;});
    });
  }
});

3. The fs.writeFile() method replaces the specified file and content if it exists. If the file does not exists a new file, containing the specified content, will be created.
- Example: Create a new file using the writeFile() method:
const fs = require('fs');
var file ='./test/newfile.htm';
var content ='<div>Html content</div>';

fs.writeFile(file, content, (err)=>{
  if(err) throw err;
  console.log('Saved.');
});

Rename file

To rename a file with the File System module, use the fs.rename() method.
Example: Rename "newfile.htm" to "renamedfile.htm":
const fs = require('fs');
var file ='./test/newfile.htm';
var newname ='./test/renamedfile.htm';

fs.rename(file, newname, (err)=>{
  if(err) throw err;
  else console.log('Renamed.');
});

Delete file

To delete a file with the File System module, use the fs.unlink() method.
Example: Delete "filename.htm" from "test/" folder:
const fs = require('fs');
var file ='./test/filename.htm';

fs.unlink(file, (err)=>{
  if(err) throw err;
  else console.log('Deleted.');
});

fs-extra module

Another option to easily work with directories and files on server, use the fs-extra module.
fs-extra adds file system methods that aren't included in the native "fs" module and adds promise support to the "fs" methods. It can be a drop in replacement for "fs".
- Before using the "fs-extra" module, you have to install it. To install "fs-extra", run this code in command line interface:
npm install --save fs-extra
Then, you can use the fs-extra module in your Node.js projects, as a drop in replacement for native fs.
const fs = require('fs-extra');
All methods in fs are attached to fs-extra. All fs methods return promises if the callback isn't passed.
Example:
const fs = require('fs-extra')
 
// Async with promises: 
fs.copy('/tmp/file.htm', '/tmp/dirx/file.htm')
.then(() => console.log('success!'))
.catch(err => console.error(err));

// Async with callbacks: 
fs.copy('/tmp/file.htm', '/tmp/dirx/file.htm', err =>{
  if (err) return console.error(err);
  console.log('success!');
});

// Sync: 
try {
  fs.copySync('/tmp/file.htm', '/tmp/dirx/file.htm');
  console.log('success!');
} catch (err){
  console.error(err);
}
- For documentation, see the fs-extra module page

Daily Test with Code Example

HTML
CSS
JavaScript
PHP-MySQL
Which tag adds a new line into a paragraph?
<b> <br> <p>
First line ...<br>
Other line...
Which CSS property can be used to add space between letters?
text-size word-spacing letter-spacing
#id {
  letter-spacing: 2px;
}
What JavaScript function can be used to get access to HTML element with a specified ID?
getElementById() getElementsByTagName() createElement()
var elm = document.getElementById("theID");
var content = elm.innerHTML;
alert(content);
Click on the "echo" correct instruction.
echo "CoursesWeb.net" echo "CoursesWeb.net"; echo ""CoursesWeb.net";
echo "Address URL: http://CoursesWeb.net";
Node.js Working with files

Last accessed pages

  1. Textarea with buttons to format text, colors and smiles (5221)
  2. Output or Force Download MP3 with PHP (5665)
  3. SHA1 Encrypt data in JavaScript (35328)
  4. PHP Unzipper - Extract Zip, Rar Archives (31748)
  5. Node.js Course (2599)

Popular pages this month

  1. Courses Web: PHP-MySQL JavaScript Node.js Ajax HTML CSS (295)
  2. Read Excel file data in PHP - PhpExcelReader (101)
  3. The Four Agreements (89)
  4. PHP Unzipper - Extract Zip, Rar Archives (87)
  5. The Mastery of Love (83)
Chat
Chat or leave a message for the other users
Full screenInchide