how to right plain text format file in node js
To write a plain text format file in Node.js, you can follow these steps:
Import the
fs
module: Thefs
module is a built-in module in Node.js that provides file system-related functionality. You can import it using therequire
keyword.javascript const fs = require('fs');
Specify the file path and content: Choose the file path where you want to create the file and specify the content you want to write to the file.
javascript const filePath = 'path/to/file.txt'; const content = 'This is the content of the file.';
Write the file: Use the
fs.writeFile()
method to write the file. This method takes the file path, content, and a callback function as parameters. The callback function is called once the file is written or if an error occurs.javascript fs.writeFile(filePath, content, (err) => { if (err) { console.error('Error writing file:', err); } else { console.log('File written successfully.'); } });
This code will create a file at the specified path and write the content to it. If an error occurs, it will be logged to the console. If the file is written successfully, a success message will be logged.
That's it! Following these steps will allow you to write a plain text format file in Node.js. Let me know if you need further assistance!