- 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 defines the clickable areas inside the image map?
<map> <img> <area>
<img src="image.jpg" usemap="#map1">
<map name="map1">
  <area shape="rect" coords="9, 120, 56, 149" href="#">
  <area shape="rect" coords="100, 200, 156, 249" href="#">
</map>
Which CSS property defines what is done if the content in a box is too big for its defined space?
display overflow position
#id {
  overflow: auto;
}
Click on the event which is triggered when the mouse is positioned over an object.
onclick onmouseover onmouseout
document.getElementById("id").onmouseover = function(){
  document.write("Have Good Life");
}
Indicate the PHP variable that contains data added in URL address after the "?" character.
$_SESSION $_GET $_POST
if(isset($_GET["id"])) {
  echo $_GET["id"];
}
Node.js Working with files

Last accessed pages

  1. Download PHP MySQL resources (936)
  2. jQuery ajax() method (13303)
  3. Using file_put_contents, file_get_contents, readfile and file() (5388)
  4. HTML5 Quick Tutorial (3645)
  5. Create simple Website with PHP (15916)

Popular pages this month

  1. Qwop (10555)
  2. Drag Racer V3 (6224)
  3. Flash Games - Free online Games (2162)
  4. List with All the Games (2073)
  5. Bubbles3 (1996)