- 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 is used to add definition lists into a <dl> element?
<dt> <dd> <li>
<dl>
 <dt>HTML</dt>
  <dd> - Hyper Text Markup Language</dd>
  <dd> - Language for web pages</dd>
</dl>
Which CSS property can hide an element on page, letting an empty space in its place?
display position visibility
#id {
  visibility: hidden;
}
Click on the event which is triggered when the mouse clicks on an object.
onclick onmouseover onfocus
document.getElementById("id").onclick = function(){
  alert("http://CoursesWeb.net/");
}
Indicate the PHP variable that contains the contents of both $_GET, $_POST, and $_COOKIE arrays.
$_SESSION $_GET $_REQUEST
if(isset($_REQUEST["id"])) {
  echo $_REQUEST["id"];
}
Node.js Working with Directories

Last accessed pages

  1. Pool Master Secure (3904)
  2. PHP MySQL - WHERE and LIKE (17547)
  3. Insert, Select and Update NULL value in MySQL (25244)
  4. Burger Bustle (369)
  5. Bob The Inventor (395)

Popular pages this month

  1. Flash Games - Free online Games (1360)
  2. Qwop (1158)
  3. Tunnel Rush (1062)
  4. Courses Web: PHP-MySQL JavaScript Ajax HTML CSS Flash-AS3 (983)
  5. Drag Racer V3 (758)