when i press the submit button value of id will get and i want to make file but its showing an error for making file
code of html file:-
<label for="">Make New File : </label>
<input type="text" id="inputfilename">
<p id="output"></p>
<br>
<button id="submitbutton" onclick="submit()">Make File</button>
code for javascript and node js:-
function submit()
{
const filename = document.getElementById("inputfilename").value;
console.log(filename);
//make file
// const filepath = `C:\Users\asus\Desktop${filesystem}`;
// console.log(filepath);
const filesystem = require('fs');
filesystem.writeFileSync('xyz.txt','Hiii',(err)=>{
if(err)
{
// console.log('Error making file...');
document.getElementById("output").innerHTML = "Error making file...";
return;
}
else
{
// console.log("File is created...");
document.getElementById("output").innerHTML = "File is created!";
}
});
}
but its showing error like this in console:-
Uncaught ReferenceError: require is not defined
at submit (indexjs.js:10:24)
at HTMLButtonElement.onclick ((index):15:50)
CodePudding user response:
When you use javascript from client side you can use Blob and file-saver module for making a file.
import { saveAs } from 'file-saver';
var blob = new Blob(["Welcome to Websparrow.org."],
{ type: "text/plain;charset=utf-8" });
saveAs(blob, "static.txt");
CodePudding user response:
Try this
html
<form onSubmit={handleSubmit}>
<label for="inputfilename">File Name: </label>
<input type="text" name="inputfilename">
<p id="content">some content</p>
<button type="submit" id="submitbutton">Make File</button>
</form>
js
const fs = require('fs');
async function handleSubmit() {
const filename = document.getElementById("inputfilename").value;
const content = document.getElementById("content").innerHTML;
try {
await fs.writeFileSync(`/Users/joe/${filename}`, content);
} catch (err) {
console.log(err);
}
}
You can look this Writing files with Node.js