Bootcamp
Search…
2.5: Disk Writing

Introduction

Writing to disk allows us to save data from our JavaScript files to our hard drives, enabling that data to persist until it is explicitly deleted.
We can make data flow from our JavaScript programs to disk and back.

Sample Code

The following code uses the Node.js fs library to write data to disk.
1
import { writeFile } from 'fs';
2
​
3
const content = 'Some content!';
4
​
5
// We often abbreviate "error" to "err" for concision.
6
const handleFileWrite = (err) => {
7
if (err) {
8
console.log(err);
9
return;
10
}
11
// If no error, file written successfully
12
console.log('success!');
13
};
14
​
15
writeFile('test.txt', content, handleFileWrite);
Copied!

Newlines

We can create newlines in text files by appending the character. The following example changes the contents of the content variable by adding newline characters in a loop.
1
let content = 'Printing 10 numbers:';
2
for (let i = 0; i < 10; i += 1) {
3
// The \n character inserts a newline at that position of the string.
4
content += `Random number: ${i}: ${Math.random()}\n`;
5
}
Copied!

Exercise

  1. 1.
  2. 2.
    Run the above code.
  3. 3.
    Open the written file in VSCode to confirm its contents are what we expect.