Experiment 1: File Operations in Node.
js
Objective: To perform file operations such as read, write, append, and delete using [Link].
Create Directry with name File _operations on Visual Studio Code
Function: [Link]()
This function writes data to a file.
If the file does not exist, it creates a new file.
If the file already exists, it overwrites the content.
create file name Write_name.js
const fs = require('fs');
// File path
const filePath = '[Link]';
// Write content to the file
[Link](filePath, 'Hello, this is a test file.', (err) => {
if (err) {
[Link]('Error writing file:', err);
} else {
[Link]('File written successfully.');
});
When you run the file will get the following output and one file [Link] will be created in the
File_operations directry
Function: [Link]()
Reads the content of a file.
Returns the data as a buffer or string (if encoding is specified).
New file with name Read_file.js
const fs = require('fs');
// File path
const filePath = '[Link]';
// Read the content of the file
[Link](filePath, 'utf8', (err, data) => {
if (err) {
[Link]('Error reading file:', err);
} else {
[Link]('File contents:', data);
});
When you run the file will get the following output
Function: [Link]()
Appends new data to an existing file.
If the file does not exist, it creates a new file and writes the data.
New file with name Append_file.js
const fs = require('fs');
// File path
const filePath = '[Link]';
// Append content to the file
[Link](filePath, '\nAdditional content appended.', (err) => {
if (err) {
[Link]('Error appending to file:', err);
} else {
[Link]('Content appended successfully.');
});
When you run the file will see the folloing output
Note: to see the content appended run Read_file.js again
Function: [Link]()
Deletes a file from the filesystem.
New file with name Delete_file.js
const fs = require('fs');
// File path
const filePath = '[Link]';
// Delete the file
[Link](filePath, (err) => {
if (err) {
[Link]('Error deleting file:', err);
} else {
[Link]('File deleted successfully.');
});
When you run the file will see the following output