Create File with Requested Form Data
When users submit form data, we can save it in a file using Node.js. There are two ways to create files: Synchronous and Asynchronous.
Synchronous File Creation
let dataString =
"My name is " +
readableData.name +
" and my email is " +
readableData.email;
fs.writeFileSync("text/" + readableData.name + ".txt", dataString);
console.log("File Created");
dataString
: combines name and email from the form.writeFileSync
: writes data to file in a blocking way (waits till complete)."text/" + readableData.name + ".txt"
: file name is based on user input.
Asynchronous File Creation
fs.writeFile(
"text/" + readableData.name + ".txt",
dataString,
"utf-8",
(err) => {
if (err) {
resp.end("Internal Server Error");
return false;
} else {
console.log("File Created");
}
}
);
writeFile
: non-blocking (code runs while file is being created)."utf-8"
: encoding type.- Callback handles success or error.