How to Save Text to A File in Node.js
In this tutorial, you'll learn how to save text to a file in Node.js using the built-in File System module.
Code Example
Here is a quick code example, saving the text "Hello There!" to a file named my_test.txt:
import fs from "node:fs";
const my_string = "Hello There!";
fs.writeFile("my_test.txt", my_string, (err) => {
if (err) {
console.error(err);
}
console.log("Done!");
});
First, we import Node.js' built-in File System module. Second, we create a string variable named my_string with a value of "Hello There!" Third, we call the writeFile()
method within the File System module and save the text to a new file named "my_test.txt"
In the callback method, we check whether an error occurred when saving the file and output it to the console. Otherwise, we tell the user we're done and exit the application.
Update package.json Configuration
Update your project's package.json
file to include the following configuration:
{
"type": "module"
}
If you do not specify the application type as a module, you'll receive the following error and the application will not execute: "SyntaxError: Cannot use import statement outside a module."
Execute the Application
Now you can execute the application from the root directory of your project. Assuming your project file is named index.js
, you can execute the application with the following command:
node index.js
If the code executed successfully, you should now have a file named my_test.txt in the root folder of your project with the text saved.
Conclusion
That's it! That's all there is to saving text to a file in Node.js.
Created: September 05, 2023
Comments
There are no comments yet. Start the conversation!