Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to import the Node.js file system module.
Node.js
const fs = require([1]); Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using incorrect module names like "file" or "filesystem".
Forgetting to put quotes around the module name.
✗ Incorrect
The correct module name to import for file system operations in Node.js is "fs".
2fill in blank
mediumComplete the code to write the string 'Hello World' to a file named 'hello.txt' asynchronously.
Node.js
fs.[1]('hello.txt', 'Hello World', (err) => { if (err) throw err; console.log('File saved!'); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using readFile instead of writeFile.
Using appendFile which adds to the file instead of replacing.
✗ Incorrect
The method to write data to a file asynchronously is writeFile.
3fill in blank
hardFix the error in the code to write 'Data' to 'data.txt' synchronously.
Node.js
fs.[1]('data.txt', 'Data');
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using readFileSync which reads instead of writes.
Using writeFile without Sync for synchronous code.
✗ Incorrect
The synchronous method to write a file is writeFileSync.
4fill in blank
hardFill both blanks to append 'More text' to 'log.txt' asynchronously and handle errors.
Node.js
fs.[1]('log.txt', 'More text', ([2]) => { if ([2]) throw [2]; console.log('Append complete'); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using writeFile which overwrites the file.
Using a callback parameter name other than 'err' or 'error'.
✗ Incorrect
appendFile is used to add data to a file without overwriting. The callback error parameter is commonly named 'err'.
5fill in blank
hardFill all three blanks to write JSON data to 'config.json' asynchronously with error handling.
Node.js
const data = JSON.stringify([1]); fs.[2]('config.json', data, ([3]) => { if ([3]) throw [3]; console.log('Config saved'); });
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong object name in JSON.stringify.
Using writeFileSync instead of writeFile.
Using a callback parameter name other than 'err'.
✗ Incorrect
We stringify the 'config' object, use writeFile to save asynchronously, and handle errors with the 'err' parameter.