Overview
- Introduction
- Loading the file system package
- Check if file or directory exists
- Reading file contents
- Writing and appending files
- Change file permissions and ownership
- Renaming/moving Files
- Deleting files
- File statistics
- Conclusion
Introduction
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));
});
Conclusion
With this information, you should be able to perform the majority of common file tasks.