File Manipulation with Node.js

Node.js is the server side version of JavaScript. Since it is not limited by the web browser, we can access files on the file system. Here are several code snippets that demonstrate how to read, write, move, delete, change ownership, change permission, check if exists, and get statistics, file size, timestamps, and ownership.

For full Node.js File System reference, see the Official Documentation.

Loading the File System Package

// This must be done before you can use any of the fs package functions below
fs = require('fs');

Check if File or Directory Exists

fs.stat('Desktop', function(err, fileStat) {
    if (err) {
        if (err.code == 'ENOENT') {
            console.log('Does not exist.');
        }
    } else {
        if (fileStat.isFile()) {
            console.log('File found.');
        } else if (fileStat.isDirectory()) {
            console.log('Directory found.');
        }
    }
});

Reading File Contents

fs.readFile('test.txt', 'utf8', function(err, fileContents) {
    if (err) throw err;
    console.log(fileContents)
});

Writing and Appending Files

fs.writeFile('test.txt', 'Hello, ', function(err) {
    if (err) throw err;
})

fs.appendFile('test.txt', 'World\n');

Change File Permissions and Ownership

// Change permission to 777
fs.chmodSync('test.txt', '777');

// Change ownership to root:root.
// It wants user and group Id number not username
// To actually run this you would need root privileges
var userId = 0;
var groupId = 0;
fs.chownSync('test.txt', userId, groupId);

Renaming/Moving Files

fs.rename('test.txt', 'test.txt.bak', function (err) {
  if (err) throw err;
  console.log('Rename complete.');
});

fs.rename('/tmp/test.txt', '/home/dtron/testCopy.txt', function (err) {
  if (err) throw err;
  console.log('Move complete.');
});

Deleting Files

fs.unlink('test.txt', function (err) {
  if (err) throw err;
  console.log('Deletion sucessful.');
});

File Statistics

// Statistics include file size, inode, uid, gid, timestamps
fs.stat('test.txt', function (err, stats) {
  if (err) throw err;
  console.log('stats: ' + JSON.stringify(stats));
});