Nodejs Course

- 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 adds an image in web page?
<div> <img> <span>
<img src="http://coursesweb.net/imgs/webcourses.gif" width="191" height="63" alt="Courses-Web" />
Which of these CSS codes displays the text oblique?
font-style: italic; text-decoration: underline; font-weight: 500;
#id {
  font-style: italic;
}
Click on the jQuery function used to hide with animation a HTML element.
click() hide() show()
$(document).ready(function() {
  $(".a_class").click(function(){ $(this).hide("slow"); });
});
Click on the correctly defined function in PHP.
fname function() {} function fname() {} function $fname() {};
function fname($a, $b) {
  echo $a * $b;
}
Node.js Working with Directories

Last accessed pages

  1. Get Time Elapsed (1885)
  2. PHP getElementById and getElementsByTagName (49154)
  3. addChild and removeChild (7902)
  4. Recursive Functions in PHP (626)
  5. Dynamic variables in JavaScript (18733)

Popular pages this month

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