The Node.js File System Module

The most common background for noders is browser based JavaScript. There's one thing that JavaScript cannot do in that context, and that is accessing the file system. It was not built into the language. It would have meant giving access to the user's private file system on her own computer, and of course we can't have that. Therefore one of the defining new things in node vis-a-vis that scenario, is precisely access to the file system.

Node.js has normalized JavaScript as a general purpose programming language in that sense. It solves problems on any computer where it may be installed. You may use it locally on your own machine, or it may be used on an internet based host to serve the hosted files of that machine to clients requesting it.

Here is a walk through of some of the central functions for doing that.

Asynchronous Read

Example 15.17. Read a File in Batch Mode, Asynchronously, reada.js
let fs = require('fs');
let filename = process.argv[2];

fs.readFile(filename, (err, data) => {
    if (err) {
        throw err;
    }
    console.log("Content:\n--------\n" + data + "\nRead asynchronously!");
});
console.log("Asynchronously?");

Asynchronous Write

Example 15.18. Write a File in Batch Mode, Asynchronously, writea.js
let fs = require('fs');
let filename = process.argv[2];

let content = `Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
`;

fs.writeFile(filename, content , (err) => {
    if (err) {
        throw err;
    }
    console.log("yes! It's written asynchronously.");
});
console.log("Asynchronously?");

Asynchronous Append

Example 15.19. Append to a File in Batch Mode, Asynchronously, writeapp.js
var fs = require('fs');
let filename = process.argv[2];

new_lines = "This data will be appended at the end of the file.";

fs.appendFile(filename, new_lines , (err) => {
    if(err) {
        throw err;
    }
    console.log('Yes. The new_content was appended successfully and asynchronously');
});
console.log("Asynchronously?");

Asynchronous Rename

Example 15.20. Rename a File in Batch Mode, Asynchronously, renamea.js
let fs = require('fs');
let oldname = process.argv[2];
let newname = process.argv[3];

fs.rename(oldname, newname, (err) => {
    if (err) {
        throw err;
    }
    console.log('Yes! File renamed successfully and asynchronously');
});

console.log("Asynchronously?");

Asynchronous Delete

Example 15.21. Delete a File in Batch Mode, Asynchronously, deletea.js
let fs = require('fs');
var filename = process.argv[2];

fs.unlink(filename, (err) => {
    if (err) {
        throw err;
    }
    console.log('Yes! File deleted successfully and asynchronously');
});
console.log('Asynchronously?');