Lecture Notes Of Class 19: File System
Operations in Node.js
Objective:
To master file system
operations in Node.js using the built-in fs (File System) module. By the end of
this class, students will learn how to read and write files, as well as perform
common directory operations such as creating directories, listing files, and
deleting files.
Overview of the fs
Module:
Node.js provides the fs
module, which allows developers to interact with the file system, making it
possible to read, write, and manipulate files and directories. The fs module
includes both synchronous and asynchronous methods. While the synchronous
methods block the program’s execution until the task is completed, the
asynchronous methods allow other code to run while waiting for the task to
complete.
We'll focus on both
synchronous and asynchronous methods to perform file system operations.
1. Reading and Writing
Files
Reading Files:
To read the contents of a
file, Node.js provides two primary methods:
- fs.readFile()
(Asynchronous)
- fs.readFileSync()
(Synchronous)
Asynchronous File Reading
with fs.readFile()
The fs.readFile() method
is non-blocking, meaning it doesn't stop the program execution while the file
is being read. Once the file is read, a callback function is called with the
file data or an error.
javascript
CopyEdit
const fs = require('fs');
// Reading a file
asynchronously
fs.readFile('example.txt',
'utf8', (err, data) => {
if (err) {
console.error('Error reading the file:',
err);
} else {
console.log('File content:', data);
}
});
- 'utf8'
specifies the encoding of the file.
- The
callback function receives two arguments: err (error) and data
(file content).
Synchronous File Reading
with fs.readFileSync()
The fs.readFileSync()
method is blocking, meaning it stops the execution of further code until the
file is fully read. It returns the content of the file directly.
javascript
CopyEdit
const fs = require('fs');
// Reading a file
synchronously
try {
const data = fs.readFileSync('example.txt',
'utf8');
console.log('File content:', data);
} catch (err) {
console.error('Error reading the file:',
err);
}
Writing Files:
Node.js provides two
primary methods for writing to files:
- fs.writeFile()
(Asynchronous)
- fs.writeFileSync()
(Synchronous)
Asynchronous File Writing
with fs.writeFile()
The fs.writeFile() method
writes data to a file. If the file doesn't exist, it will be created.
javascript
CopyEdit
const fs = require('fs');
// Writing to a file
asynchronously
fs.writeFile('output.txt',
'Hello, Node.js!', 'utf8', (err) => {
if (err) {
console.error('Error writing to the
file:', err);
} else {
console.log('File written successfully');
}
});
Synchronous File Writing
with fs.writeFileSync()
The fs.writeFileSync()
method writes data to a file and blocks the program execution until the file is
written.
javascript
CopyEdit
const fs = require('fs');
// Writing to a file
synchronously
try {
fs.writeFileSync('output.txt', 'Hello,
Node.js!', 'utf8');
console.log('File written successfully');
} catch (err) {
console.error('Error writing to the file:',
err);
}
2. Directory Operations
Node.js provides various
methods for manipulating directories such as creating, listing files, and
deleting files. These methods are also available in both synchronous and
asynchronous forms.
Creating a Directory:
- fs.mkdir()
(Asynchronous)
- fs.mkdirSync()
(Synchronous)
To create a new
directory:
javascript
CopyEdit
const fs = require('fs');
// Asynchronously
creating a directory
fs.mkdir('newDirectory', (err)
=> {
if (err) {
console.error('Error creating the
directory:', err);
} else {
console.log('Directory created
successfully');
}
});
To create a directory
synchronously:
javascript
CopyEdit
const fs = require('fs');
// Synchronously creating
a directory
try {
fs.mkdirSync('newDirectory');
console.log('Directory created
successfully');
} catch (err) {
console.error('Error creating the
directory:', err);
}
Listing Files in a
Directory:
- fs.readdir()
(Asynchronous)
- fs.readdirSync()
(Synchronous)
To list all files in a
directory:
javascript
CopyEdit
const fs = require('fs');
// Asynchronously listing
files in a directory
fs.readdir('someDirectory',
(err, files) => {
if (err) {
console.error('Error reading the
directory:', err);
} else {
console.log('Files in the directory:',
files);
}
});
To list files
synchronously:
javascript
CopyEdit
const fs = require('fs');
// Synchronously listing
files in a directory
try {
const files = fs.readdirSync('someDirectory');
console.log('Files in the directory:',
files);
} catch (err) {
console.error('Error reading the
directory:', err);
}
Deleting a File:
- fs.unlink()
(Asynchronous)
- fs.unlinkSync()
(Synchronous)
To delete a file:
javascript
CopyEdit
const fs = require('fs');
// Asynchronously
deleting a file
fs.unlink('output.txt', (err)
=> {
if (err) {
console.error('Error deleting the
file:', err);
} else {
console.log('File deleted successfully');
}
});
To delete a file
synchronously:
javascript
CopyEdit
const fs = require('fs');
// Synchronously deleting
a file
try {
fs.unlinkSync('output.txt');
console.log('File deleted successfully');
} catch (err) {
console.error('Error deleting the file:',
err);
}
Lab Tasks
Task 1: Read from and
Write to Files Using the fs Module
1.
Create a file named task1.txt and write
some content to it using fs.writeFile().
2.
Read the content of task1.txt using fs.readFile(),
and display the content in the console.
Task 2: Implement
Directory Operations
1.
Create a new directory called taskDirectory.
2.
List the files in the current directory.
3.
Delete a file (for example, task1.txt)
after reading it.
4.
Create and delete another directory called
tempDirectory.
Conclusion:
By the end of this class,
you should be familiar with performing essential file system operations in
Node.js. These include reading and writing files, creating and listing
directories, and deleting files. These operations are fundamental to many
applications, especially those that deal with managing files and directories.
4o mini
You said:
Answer this...Lab Tasks Task
1: Read from and Write to Files Using the fs Module Create a file named
task1.txt and write some content to it using fs.writeFile(). Read the content
of task1.txt using fs.readFile(), and display the content in the console. Task
2: Implement Directory Operations Create a new directory called taskDirectory.
List the files in the current directory. Delete a file (for example, task1.txt)
after reading it. Create and delete another directory called tempDirectory.
ChatGPT said:
ChatGPT
Lab Tasks
Task 1: Read from and
Write to Files Using the fs Module
1.
Create a file named task1.txt and
write some content to it using fs.writeFile().
To create a file named task1.txt
and write content to it, you can use the fs.writeFile() method. This method
writes data to the file asynchronously.
javascript
CopyEdit
const fs = require('fs');
// Writing to the file
task1.txt
fs.writeFile('task1.txt',
'This is the content of task1.txt', 'utf8', (err) => {
if (err) {
console.error('Error writing to the
file:', err);
} else {
console.log('Content written to
task1.txt successfully');
}
});
- This
code will create a file named task1.txt in the current directory and write
the string "This is the content of task1.txt" to it.
2.
Read the content of task1.txt using fs.readFile(),
and display the content in the console.
Now, you can read the
content of the file using the fs.readFile() method:
javascript
CopyEdit
const fs = require('fs');
// Reading from the file
task1.txt
fs.readFile('task1.txt', 'utf8',
(err, data) => {
if (err) {
console.error('Error reading the file:',
err);
} else {
console.log('Content of task1.txt:',
data);
}
});
- This
code will read the content of task1.txt and print it to the console.
Task 2: Implement
Directory Operations
1.
Create a new directory called taskDirectory.
To create a directory
named taskDirectory, you can use fs.mkdir():
javascript
CopyEdit
const fs = require('fs');
// Create a directory
named taskDirectory
fs.mkdir('taskDirectory',
(err) => {
if (err) {
console.error('Error creating the
directory:', err);
} else {
console.log('Directory taskDirectory
created successfully');
}
});
- This
code will create a new directory named taskDirectory in the current
directory.
2.
List the files in the current
directory.
To list all files in the
current directory, you can use fs.readdir():
javascript
CopyEdit
const fs = require('fs');
// List all files in the
current directory
fs.readdir('.', (err,
files) => {
if (err) {
console.error('Error reading the
directory:', err);
} else {
console.log('Files in the current
directory:', files);
}
});
- This
code will print all the files and directories in the current working
directory.
3.
Delete a file (task1.txt) after
reading it.
To delete the task1.txt
file, you can use fs.unlink() after reading the file.
javascript
CopyEdit
const fs = require('fs');
// Read the content of
task1.txt before deleting it
fs.readFile('task1.txt', 'utf8',
(err, data) => {
if (err) {
console.error('Error reading the file:',
err);
} else {
console.log('Content of task1.txt:',
data);
// Now, delete the file task1.txt
fs.unlink('task1.txt', (err) => {
if (err) {
console.error('Error deleting
the file:', err);
} else {
console.log('File task1.txt
deleted successfully');
}
});
}
});
- This
code reads the content of task1.txt and then deletes it from the file
system.
4.
Create and delete another directory
called tempDirectory.
To create and delete the tempDirectory,
you can use fs.mkdir() for creation and fs.rmdir() for deletion.
javascript
CopyEdit
const fs = require('fs');
// Create a directory
named tempDirectory
fs.mkdir('tempDirectory',
(err) => {
if (err) {
console.error('Error creating the
directory:', err);
} else {
console.log('Directory tempDirectory
created successfully');
// Delete the directory tempDirectory
fs.rmdir('tempDirectory', (err) => {
if (err) {
console.error('Error deleting
the directory:', err);
} else {
console.log('Directory
tempDirectory deleted successfully');
}
});
}
});
- This
code will create a new directory named tempDirectory and then delete it
once the creation is successful.
Summary:
- Task
1: We wrote content to task1.txt and read the
content from it using fs.writeFile() and fs.readFile().
- Task
2: We performed directory operations by creating taskDirectory,
listing files, deleting task1.txt, and creating and deleting tempDirectory.
By completing these
tasks, you now have experience using the fs module for file and directory
operations in Node.js.
4o mini
You said:
Write 10 assignments with
solution and explanation in detail on above concept
ChatGPT said:
ChatGPT
Here are 10 assignments
with detailed explanations and solutions based on File System Operations in
Node.js using the fs module:
Assignment 1: Create and
Write to a File
Problem:
Create a file named example.txt and write "Node.js File System
Operations" into it. If the file already exists, replace the content with
the new text.
Solution:
javascript
CopyEdit
const fs = require('fs');
// Write content to the
file
fs.writeFile('example.txt',
'Node.js File System Operations', 'utf8', (err) => {
if (err) {
console.error('Error writing to the
file:', err);
} else {
console.log('File created and content
written successfully');
}
});
Explanation:
We use fs.writeFile() to write content to example.txt. If the file exists, it
will be overwritten with the new text. If the file doesn't exist, it will be
created.
Assignment 2: Read File
Content
Problem:
Read the content of the example.txt file and print it to the console.
Solution:
javascript
CopyEdit
const fs = require('fs');
// Read the content of
the file
fs.readFile('example.txt',
'utf8', (err, data) => {
if (err) {
console.error('Error reading the file:',
err);
} else {
console.log('File content:', data);
}
});
Explanation:
fs.readFile() reads the content of the file asynchronously. The callback
function receives the file data as the second argument and prints it to the
console.
Assignment 3: Append Data
to an Existing File
Problem:
Append the text "This is a new line." to the example.txt file.
Solution:
javascript
CopyEdit
const fs = require('fs');
// Append data to the
file
fs.appendFile('example.txt',
'\nThis is a new line.', 'utf8', (err) => {
if (err) {
console.error('Error appending to the
file:', err);
} else {
console.log('Content appended
successfully');
}
});
Explanation:
We use fs.appendFile() to append data to an existing file. If the file doesn't
exist, it will be created, and the text will be written.
Assignment 4: Check if a
File Exists
Problem:
Check if a file named example.txt exists in the current directory and print a
message if it exists or not.
Solution:
javascript
CopyEdit
const fs = require('fs');
// Check if the file
exists
fs.access('example.txt',
fs.constants.F_OK, (err) => {
if (err) {
console.log('example.txt does not
exist');
} else {
console.log('example.txt exists');
}
});
Explanation:
fs.access() checks if the file exists. The constant fs.constants.F_OK checks if
the file is visible to the process (i.e., exists).
Assignment 5: Create a
Directory
Problem:
Create a new directory named myDirectory.
Solution:
javascript
CopyEdit
const fs = require('fs');
// Create a directory
fs.mkdir('myDirectory', (err)
=> {
if (err) {
console.error('Error creating
directory:', err);
} else {
console.log('Directory created
successfully');
}
});
Explanation:
fs.mkdir() creates a new directory. If the directory already exists, an error
will be thrown.
Assignment 6: List All
Files in a Directory
Problem:
List all files and directories in the current directory.
Solution:
javascript
CopyEdit
const fs = require('fs');
// List files in the
current directory
fs.readdir('.', (err,
files) => {
if (err) {
console.error('Error reading the
directory:', err);
} else {
console.log('Files in the current
directory:', files);
}
});
Explanation:
fs.readdir() lists all the files and directories in the specified directory (in
this case, the current directory .). It returns an array of filenames.
Assignment 7: Delete a
File
Problem:
Delete the example.txt file.
Solution:
javascript
CopyEdit
const fs = require('fs');
// Delete the file
fs.unlink('example.txt', (err)
=> {
if (err) {
console.error('Error deleting the
file:', err);
} else {
console.log('File deleted successfully');
}
});
Explanation:
fs.unlink() deletes the specified file. If the file doesn't exist, it will
throw an error.
Assignment 8: Rename a
File
Problem:
Rename the example.txt file to newExample.txt.
Solution:
javascript
CopyEdit
const fs = require('fs');
// Rename the file
fs.rename('example.txt', 'newExample.txt',
(err) => {
if (err) {
console.error('Error renaming the
file:', err);
} else {
console.log('File renamed successfully');
}
});
Explanation:
fs.rename() is used to rename or move a file. If the destination file already
exists, it will be replaced.
Assignment 9: Delete an
Empty Directory
Problem:
Delete an empty directory named myDirectory.
Solution:
javascript
CopyEdit
const fs = require('fs');
// Delete an empty
directory
fs.rmdir('myDirectory', (err)
=> {
if (err) {
console.error('Error deleting the
directory:', err);
} else {
console.log('Directory deleted
successfully');
}
});
Explanation:
fs.rmdir() deletes an empty directory. If the directory contains files or other
directories, it will throw an error.
Assignment 10: Create a
Nested Directory
Problem:
Create a nested directory structure: parentDirectory/childDirectory.
Solution:
javascript
CopyEdit
const fs = require('fs');
// Create nested
directories
fs.mkdir('parentDirectory/childDirectory',
{ recursive: true }, (err) => {
if (err) {
console.error('Error creating nested
directories:', err);
} else {
console.log('Nested directories created
successfully');
}
});
Explanation:
The { recursive: true } option ensures that the parent directory is created if
it doesn't already exist. This allows us to create nested directories in one
go.
Conclusion:
These assignments provide
hands-on experience in performing various file and directory operations using
the fs module in Node.js. By practicing these tasks, students will gain a
better understanding of how to interact with the file system in Node.js for
real-world applications.
4o mini
You said:
write 50 MCQs for the
concept above with explanation
ChatGPT said:
ChatGPT
Here are 50
multiple-choice questions (MCQs) based on File System Operations in Node.js
with detailed explanations for each answer.
1. What does the fs
module in Node.js allow you to do?
a) Create and manage HTTP
requests
b) Interact with the file system
c) Handle events
d) Create and manage servers
Answer:
b) Interact with the file system
Explanation: The fs (File System) module provides an API for interacting
with the file system, such as reading, writing, and manipulating files and
directories.
2. Which of the following
methods is used to write data to a file in Node.js?
a) fs.createFile()
b) fs.writeFile()
c) fs.appendFile()
d) fs.writeToFile()
Answer:
b) fs.writeFile()
Explanation: The fs.writeFile() method is used to write data to a file,
creating the file if it doesn't exist or overwriting the existing file if it
does.
3. What does fs.readFile()
do in Node.js?
a) Reads content from a
file and logs it to the console
b) Reads the file system
c) Reads the content of a file asynchronously
d) Reads and writes data to a file
Answer:
c) Reads the content of a file asynchronously
Explanation: fs.readFile() reads the content of a file asynchronously
and invokes a callback function with the file's data or error.
4. Which function is used
to check if a file exists in Node.js?
a) fs.exists()
b) fs.checkFile()
c) fs.access()
d) fs.fileExists()
Answer:
c) fs.access()
Explanation: The fs.access() method checks if a file exists and is
accessible with the specified permissions (e.g., read/write).
5. Which method is used
to append data to a file in Node.js?
a) fs.appendFile()
b) fs.writeFile()
c) fs.addFile()
d) fs.writeAppend()
Answer:
a) fs.appendFile()
Explanation: fs.appendFile() is used to append data to a file. If the
file doesn't exist, it will be created.
6. What does fs.unlink()
do?
a) Creates a new file
b) Reads a file
c) Deletes a file
d) Renames a file
Answer:
c) Deletes a file
Explanation: fs.unlink() deletes a specified file. If the file doesn't
exist, it throws an error.
7. Which method is used
to create a new directory in Node.js?
a) fs.createDirectory()
b) fs.mkdir()
c) fs.createDir()
d) fs.newDir()
Answer:
b) fs.mkdir()
Explanation: fs.mkdir() creates a new directory. If the directory
already exists, it will throw an error unless the recursive option is used.
8. What does the recursive
option in fs.mkdir() allow you to do?
a) Delete files
recursively
b) Create nested directories
c) Write to multiple files at once
d) Check file permissions recursively
Answer:
b) Create nested directories
Explanation: The recursive: true option allows for creating nested
directories in one go (i.e., if the parent directory doesn't exist, it will be
created automatically).
9. How do you list all
files in a directory using Node.js?
a) fs.listFiles()
b) fs.readdir()
c) fs.readFiles()
d) fs.getFiles()
Answer:
b) fs.readdir()
Explanation: fs.readdir() lists all files and directories in the
specified directory.
10. Which function is
used to remove a directory in Node.js?
a) fs.removeDir()
b) fs.deleteDir()
c) fs.rmdir()
d) fs.removeDirectory()
Answer:
c) fs.rmdir()
Explanation: fs.rmdir() removes an empty directory. If the directory
contains files, it will throw an error.
11. How can you read the
content of a file synchronously?
a) fs.readFileSync()
b) fs.readSyncFile()
c) fs.syncReadFile()
d) fs.syncFile()
Answer:
a) fs.readFileSync()
Explanation: fs.readFileSync() reads the content of a file
synchronously, blocking the execution until the file is read.
12. Which of the
following is a valid way to check if a file exists in Node.js?
a) fs.checkFile('file.txt')
b) fs.isFile('file.txt')
c) fs.existsSync('file.txt')
d) fs.fileExists('file.txt')
Answer:
c) fs.existsSync('file.txt')
Explanation: fs.existsSync() is a synchronous method used to check if a
file or directory exists.
13. How do you delete an
empty directory in Node.js?
a) fs.deleteDirectory()
b) fs.remove()
c) fs.rmdir()
d) fs.removeDir()
Answer:
c) fs.rmdir()
Explanation: fs.rmdir() is used to delete an empty directory. To delete
a non-empty directory, you need to remove its contents first.
14. Which method is used
to rename or move a file?
a) fs.changeName()
b) fs.rename()
c) fs.move()
d) fs.modifyFile()
Answer:
b) fs.rename()
Explanation: fs.rename() is used to rename or move a file or directory.
15. What does fs.stat()
return?
a) File content
b) File information (such as size, creation time)
c) File permissions
d) File name
Answer:
b) File information (such as size, creation time)
Explanation: fs.stat() retrieves information about a file, such as its
size, creation time, and permissions.
16. What is the default
encoding used in fs.readFile() and fs.writeFile()?
a) UTF-16
b) ASCII
c) UTF-8
d) Base64
Answer: c)
UTF-8
Explanation: The default encoding for fs.readFile() and fs.writeFile()
is UTF-8.
17. Which method is used
to create a file stream in Node.js?
a) fs.stream()
b) fs.createStream()
c) fs.createReadStream()
d) fs.openFileStream()
Answer:
c) fs.createReadStream()
Explanation: fs.createReadStream() is used to create a readable stream
to read data from a file.
18. What happens when you
call fs.writeFile() on an existing file?
a) The file is renamed
b) The file's content is replaced with new content
c) The file's permissions are modified
d) An error is thrown
Answer:
b) The file's content is replaced with new content
Explanation: If the file already exists, fs.writeFile() will overwrite
the existing content with the new content.
19. What does fs.mkdirSync()
do?
a) Creates a file
synchronously
b) Creates a directory synchronously
c) Lists directories synchronously
d) Renames a directory synchronously
Answer:
b) Creates a directory synchronously
Explanation: fs.mkdirSync() is the synchronous version of fs.mkdir(),
which creates a directory and blocks further execution until the directory is
created.
20. How can you create a
file stream for writing data to a file in Node.js?
a) fs.createWriteStream()
b) fs.writeStream()
c) fs.openWriteStream()
d) fs.createStream()
Answer:
a) fs.createWriteStream()
Explanation: fs.createWriteStream() is used to create a writable stream
for writing data to a file.
21. How do you read the
content of a file synchronously?
a) fs.readSync()
b) fs.readFileSync()
c) fs.read()
d) fs.syncReadFile()
Answer:
b) fs.readFileSync()
Explanation: fs.readFileSync() is used to read the content of a file
synchronously, blocking the execution until the file is read.
22. What is the return
value of fs.readdir()?
a) An array of file
descriptors
b) An array of file paths
c) An array of file names
d) A string with file contents
Answer:
c) An array of file names
Explanation: fs.readdir() returns an array containing the names of all
files and directories in the specified directory.
23. What is the default
behavior of fs.rmdir() if the directory is not empty?
a) It removes the
directory and its contents
b) It throws an error
c) It lists all contents of the directory
d) It renames the directory
Answer:
b) It throws an error
Explanation: fs.rmdir() will throw an error if the directory is not
empty. To remove a non-empty directory, the contents must be deleted first.
24. How can you monitor
changes to a file or directory?
a) Using fs.watch()
b) Using fs.observe()
c) Using fs.track()
d) Using fs.monitor()
Answer:
a) Using fs.watch()
Explanation: fs.watch() allows you to monitor a file or directory for
changes and execute a callback when changes occur.
25. Which method is used
to rename a file synchronously in Node.js?
a) fs.renameSync()
b) fs.rename()
c) fs.moveSync()
d) fs.renameFileSync()
Answer:
a) fs.renameSync()
Explanation: fs.renameSync() renames a file synchronously, blocking
further execution until the file is renamed.
I will continue
generating the remaining MCQs in the next response.
26. What does fs.appendFileSync()
do?
a) Writes data to a file
asynchronously
b) Appends data to a file synchronously
c) Creates a file synchronously
d) Reads a file synchronously
Answer:
b) Appends data to a file synchronously
Explanation: fs.appendFileSync() appends data to a file synchronously.
If the file doesn't exist, it is created.
27. How do you check if a
file is a directory in Node.js?
a) fs.isDirectory()
b) fs.isFile()
c) fs.statSync()
d) fs.checkDirectory()
Answer:
c) fs.statSync()
Explanation: You can use fs.statSync() to get the file information, and
check the isDirectory() method of the returned stats object to determine if the
file is a directory.
28. Which method can be
used to create a writable stream to a file?
a) fs.createFileStream()
b) fs.createWriteStream()
c) fs.writeToStream()
d) fs.streamWrite()
Answer:
b) fs.createWriteStream()
Explanation: fs.createWriteStream() is used to create a writable stream
to a file. You can use it to write data to a file in chunks.
29. What happens if you
try to read a file that does not exist using fs.readFile()?
a) It returns an empty
string
b) It throws an error
c) It creates a new file
d) It returns null
Answer:
b) It throws an error
Explanation: If you attempt to read a non-existing file using fs.readFile(),
it will throw an error indicating that the file does not exist.
30. What does the fs.copyFile()
method do?
a) Copies a file
asynchronously
b) Moves a file
c) Renames a file
d) Creates a duplicate of a file with a different name
Answer:
a) Copies a file asynchronously
Explanation: fs.copyFile() copies the content of one file to another
asynchronously.
31. What does fs.writeFileSync()
do?
a) Writes data to a file
asynchronously
b) Creates a file if it doesn't exist
c) Writes data to a file synchronously
d) Reads data from a file synchronously
Answer:
c) Writes data to a file synchronously
Explanation: fs.writeFileSync() writes data to a file synchronously,
blocking further execution until the file is written.
32. Which method is used
to rename a file asynchronously in Node.js?
a) fs.renameSync()
b) fs.rename()
c) fs.changeFileName()
d) fs.moveFile()
Answer:
b) fs.rename()
Explanation: fs.rename() is used to rename or move a file
asynchronously. If the operation is successful, the callback is executed.
33. Which of the
following is a valid use of fs.access()?
a) Check if a file exists
and has write permission
b) Read the content of a file
c) Write data to a file
d) Rename a file
Answer:
a) Check if a file exists and has write permission
Explanation: fs.access() checks if a file is accessible, using the
specified permission flags (e.g., read, write).
34. What is the default
encoding used when writing data to a file using fs.writeFile()?
a) UTF-8
b) Base64
c) ASCII
d) Binary
Answer:
a) UTF-8
Explanation: By default, fs.writeFile() writes data with UTF-8 encoding.
You can specify a different encoding if needed.
35. What is returned by fs.readdirSync()?
a) A string representing
the file's contents
b) A list of file descriptors
c) A list of file names in a directory
d) A buffer of file contents
Answer:
c) A list of file names in a directory
Explanation: fs.readdirSync() returns an array of filenames in a
directory.
36. Which method is used
to check the statistics of a file asynchronously in Node.js?
a) fs.stats()
b) fs.statSync()
c) fs.stat()
d) fs.checkStats()
Answer:
c) fs.stat()
Explanation: fs.stat() checks the statistics of a file asynchronously,
including its size, creation time, and permissions.
37. How do you create a
directory asynchronously in Node.js?
a) fs.createDirectory()
b) fs.mkdir()
c) fs.newDir()
d) fs.makeDir()
Answer:
b) fs.mkdir()
Explanation: fs.mkdir() is used to create a directory asynchronously.
38. What method allows
you to watch a file or directory for changes?
a) fs.watchFile()
b) fs.monitor()
c) fs.watch()
d) fs.track()
Answer:
c) fs.watch()
Explanation: fs.watch() watches a file or directory for changes and
triggers a callback when modifications occur.
39. What happens when you
call fs.writeFile() on a read-only file?
a) It succeeds without
errors
b) It throws an error
c) It appends data to the file
d) It renames the file
Answer:
b) It throws an error
Explanation: fs.writeFile() will throw an error if you attempt to write
to a read-only file.
40. How do you delete a
file synchronously in Node.js?
a) fs.removeSync()
b) fs.deleteSync()
c) fs.unlinkSync()
d) fs.unlink()
Answer:
c) fs.unlinkSync()
Explanation: fs.unlinkSync() deletes a file synchronously. If the file
doesn't exist, it throws an error.
41. What does fs.createReadStream()
return?
a) A file object
b) A readable stream
c) A writable stream
d) A buffer of file contents
Answer:
b) A readable stream
Explanation: fs.createReadStream() returns a readable stream, which can
be used to read data from a file in chunks.
42. Which of the
following methods is used to watch for file changes in a directory?
a) fs.watchDirectory()
b) fs.observe()
c) fs.watch()
d) fs.directoryWatch()
Answer:
c) fs.watch()
Explanation: fs.watch() is used to monitor a file or directory for
changes and triggers a callback when modifications occur.
43. What is the purpose
of fs.chmod()?
a) Change file content
b) Change file size
c) Change file permissions
d) Change file name
Answer:
c) Change file permissions
Explanation: fs.chmod() is used to change the permissions of a file or
directory.
44. Which method is used
to check if a file exists and has the specified permissions?
a) fs.exists()
b) fs.fileExist()
c) fs.access()
d) fs.checkFile()
Answer:
c) fs.access()
Explanation: fs.access() checks whether a file exists and whether it has
the specified permissions, such as read or write access.
45. How do you remove a
file asynchronously in Node.js?
a) fs.deleteFile()
b) fs.removeFile()
c) fs.unlink()
d) fs.remove()
Answer:
c) fs.unlink()
Explanation: fs.unlink() is used to delete a file asynchronously.
46. How do you check if a
file is a symbolic link?
a) fs.isSymbolicLink()
b) fs.statSync()
c) fs.isLink()
d) fs.linkCheck()
Answer:
b) fs.statSync()
Explanation: fs.statSync() checks the stats of a file and can be used to
check if the file is a symbolic link using the isSymbolicLink() method of the
returned stats object.
47. Which method is used
to close a file descriptor in Node.js?
a) fs.close()
b) fs.end()
c) fs.closeFile()
d) fs.delete()
Answer:
a) fs.close()
Explanation: fs.close() is used to close an open file descriptor.
48. What is the return
value of fs.writeFile()?
a) String
b) File path
c) File content
d) Undefined
Answer:
d) Undefined
Explanation: fs.writeFile() does not return any value. It executes a
callback function after writing data to a file.
49. Which of the
following methods is used to append data to a file in Node.js?
a) fs.appendData()
b) fs.appendFile()
c) fs.writeFile()
d) fs.createFile()
Answer:
b) fs.appendFile()
Explanation: fs.appendFile() appends data to a file if it exists, or
creates the file if it does not.
50. Which method can be
used to change the ownership of a file in Node.js?
a) fs.chown()
b) fs.rename()
c) fs.move()
d) fs.setOwner()
Answer:
a) fs.chown()
Explanation: fs.chown() is used to change the ownership of a file in
Node.js.

No comments:
Post a Comment