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 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 Directories

Last accessed pages

  1. Date and Time in ActionScript 3 (9973)
  2. PHP PDO - exec (INSERT, UPDATE, DELETE) MySQL (55419)
  3. Execute JavaScript scripts loaded via AJAX (7844)
  4. Create simple Website with PHP (43829)
  5. KeyboardEvent - Events for Keyboard (1692)

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 (86)
  5. The Mastery of Love (83)