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");
  1. dataString: combines name and email from the form.
  2. writeFileSync: writes data to file in a blocking way (waits till complete).
  3. "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");
}
}
);
  1. writeFile: non-blocking (code runs while file is being created).
  2. "utf-8": encoding type.
  3. Callback handles success or error.