-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.js
More file actions
28 lines (25 loc) · 734 Bytes
/
file.js
File metadata and controls
28 lines (25 loc) · 734 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const fs = require('fs');
const filename = 'example100.txt';
const initialData = 'Hello, Node.js!';
// Read file
fs.readFile(filename, 'utf8', (err, data) => {
if (err) {
// If file doesn't exist, create it and add initial data
if (err.code === 'ENOENT') {
console.log(`${filename} does not exist. Creating the file...`);
fs.writeFile(filename, initialData, err => {
if (err) throw err;
console.log(`${filename} created with initial data.`);
});
return;
}
// Handle other errors
throw err;
}
console.log(data);
});
// Write to file
fs.writeFile(filename, 'Hello, Node.js!', { flag: 'a' }, err => {
if (err) throw err;
console.log('Data appended to file.');
});