Bootcamp
Search…
2.6: Disk Altering

Introduction

In order to write a complete program that processes a file, we need both file read and write.
Data flow between Node.js and hard drive is same regardless of writing new files or altering existing files.
We'll first read the file into our program, then write the final version back out. The following example uses a function addToEndOfLine to add a random number to the end of each line in a file.
1
import { readFile, writeFile } from 'fs';
2
​
3
const filename = 'alter.txt';
4
​
5
/**
6
* Split text by lines, add a number to the end of each line, return new text.
7
* @param text - Original string
8
* @returns modified string
9
*/
10
const addToEndOfLine = (text) => {
11
// Split text into array where each element is new line.
12
const lines = text.split('\n');
13
​
14
// newText stores the modified text.
15
let newText = '';
16
​
17
for (let i = 0; i < lines.length; i += 1) {
18
// Add the original line in text to newText
19
newText += lines[i];
20
​
21
// Add a random number to the end of this line
22
newText += `${Math.random()}\n`;
23
}
24
​
25
// Return modified text
26
return newText;
27
};
28
​
29
/**
30
* Process content and write new content back to original file
31
* @param readErr - Reading error if any
32
* @param content - Original file content
33
* @returns undefined
34
*/
35
const handleFileRead = (readErr, content) => {
36
// Log original file content
37
console.log(content);
38
​
39
// Catch reading error if any
40
if (readErr) {
41
console.log('reading error', readErr);
42
}
43
​
44
// Process content
45
const newContent = addToEndOfLine(content);
46
​
47
// Write processed content back to the file, replacing old content
48
writeFile(filename, newContent, (writeErr) => {
49
// Catch writing error if any
50
if (writeErr) {
51
console.log('error writing', newContent, writeErr);
52
return;
53
}
54
console.log('success!');
55
});
56
};
57
​
58
readFile(filename, 'utf-8', handleFileRead);
Copied!

Further Reading

Node fs module:

Exercise

  1. 1.
  2. 2.
    Create a file in the repo alter.txt with sample content.
  3. 3.
    Run the above code.
  4. 4.
    Open the altered file in VSCode to confirm its contents are what we expect.