- Create new Directory
- Rename directory
- Delete directory
- fs-extra module

Read Directory Contents

The fs.readdirSync(dir) method can be used to read Synchronously the contents of a directory. Returns an array of the names of the files and folders in the passed directory ("dir"), excluding '.' and '..'..
Example: The dirCnt() function from this example returns an object with the folders and files in the directory in which this code is running:
//returns object with folders and files in $dir {root:'dir_path', d:[],  f:[]}
var dirCnt = (dir)=>{
  //include the fs, path modules
  var fs = require('fs');
  var path = require('path');
  var re ={root:path.resolve(dir), d:[], f:[]};

  //traverses the list with folders and files, and add them in $re
  fs.readdirSync(dir).forEach((f)=>{
    var df = path.resolve(dir, f); //set the path of the file/folder

    //check if $df is file or directory
    var stats = fs.statSync(df);
    if(stats.isFile()) re.f.push(f);
    else if(stats.isDirectory()) re.d.push(f);
  });
  return re;
};

//get the folder and files of the directory where this file is located
var df = dirCnt(__dirname);
console.log(df);
Save the code above in a file called "read_dir.js", and run the file in command line interface.
You'll get a result like in this screenshoot:
node.js read directory

Create new Directory

To create a new directory, you can use the fs.mkdir() or fs.mkdirSync() method.
Here is an exemple with a function that can be used to create new directory:
//creates in $base the directory $dirname; Returns string message
var createDir = (base, dirname)=>{
  //include the fs, path modules
  var fs = require('fs');
  var path = require('path');
  var dir = path.resolve(base, dirname);
  var re ='The directory: '+ dir +'/ already exists';

  if(!fs.existsSync(dir)){
    fs.mkdirSync(dir, 0755);
    re = fs.existsSync(dir) ?'Successfully created: '+ dir :'Unable to create: '+ dir;
  }
  return re;
};

//creates a folder called 'newdir' in the directory where this file is located
var mkdir = createDir(__dirname, 'newdir');
console.log(mkdir);

Rename directory

To rename a directory with the File System module, use the fs.rename(oldPath, newPath, callback) method.
Example: Rename "dir_1" folder (located in "/test") to "renamed_dir":
const fs = require('fs');
var old_d ='./test/dir_1';
var new_d ='./test/renamed_dir';

fs.rename(old_d, new_d, (err)=>{
  if(err) throw err;
  console.log('Renamed.');
});

Delete directory

To delete a directory, you can use this removeDir() function:
/*
Remove a Directory Asynchronously
 - dir = path to directory to delete
 - recursive = true or false;
   True - will remove recursively the entire directory;
   False - delete only the files in specified directory
 - callback = (optional) callback function; receives an argument for returned response
*/
function removeDir(dir, recursive, callback){
  const fs = require('fs');
  const path = require('path');
  var nr =0; //to call the callback only once

  function delFile(dir, file){
    return new Promise(function (resolve, reject){
      var filePath = path.join(dir, file);
      fs.lstat(filePath, function(err, stats){
        if(err) return reject(err);
        if(recursive===true && stats.isDirectory()) resolve(delDir(filePath));
        else if(stats.isFile()){
          fs.unlink(filePath, function(err){
            if(err) return reject(err);
            resolve();
          });
        }
        nr++;
        if(recursive===false && nr==1) return callback ? callback('Files deleted') :resolve();
      });
    });
  };

  function delDir(dir){
    return new Promise(function(resolve, reject){
      fs.access(dir, function(err){
        if(err) return callback ? callback(err) :reject(err);
        fs.readdir(dir, function(err, files){
          if(err) return callback ? callback(err) :reject(err);
          Promise.all(files.map(function(file){
            return delFile(dir, file);
          })).then(function(){
            if(recursive===true){
              fs.rmdir(dir, function(err){
                if(err) return callback ? callback(err) :reject(err);
                if(callback) resolve(callback('Deleted: '+dir));
                else resolve('Deleted: '+dir);
              });
            }
            else resolve();
          }).catch(reject);
        });
      });
    });
  };
  return delDir(dir);
}
- This removeDir() function can delete recursively the entire directory, or just its files.
Example usage:
- Remove recursively the entire '.test/dirx/' directory:
// here add the removeDir() function

removeDir('./test/dirx/', true, function(re){console.log(re);});
- Delete only the files in '.test/dirx/' directory:
// here add the removeDir() function

removeDir('./test/dirx/', false, function(re){console.log(re);});

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/dirname/', '/dirx/dirname/')
.then(() => console.log('success!'))
.catch(err => console.error(err));
 
// Async with callbacks: 
fs.copy('/tmp/dirname/', '/dirx/dirname/', err =>{
  if (err) return console.error(err);
  console.log('success!');

// Sync: 
try {
  fs.copySync('/tmp/dirname/', '/dirx/dirname/');
  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 Directories

Last accessed pages

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

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)