[英]Connecting HTML/DOM with node.js
I'm trying to find a way to write to a text file using node.js but I was trying to get the input from the HTML DOM.我试图找到一种使用 node.js 写入文本文件的方法,但我试图从 HTML DOM 获取输入。 How do you write the output from the DOM to a text file using fs.writeFile?
如何使用 fs.writeFile 将 output 从 DOM 写入文本文件?
Here's some code that doesn't work but thought it might be relevant.这是一些不起作用的代码,但认为它可能是相关的。 Thanks
谢谢
<h3>A demonstration of how to access a Text Field</h3>
<input id="myText">
<button onclick="myFunction()">Try it</button>
<script>
const fs = require('fs')
function myFunction() {
var content = document.getElementById("myText").value;
}
fs.writeFile('./test.txt', content, err => {
if(err){
console.log(err);
return
}
})
</script>
You cannot write file directly from a browser to local computers.您不能直接从浏览器将文件写入本地计算机。
That would be a massive security concern.这将是一个巨大的安全问题。
*You also cannot use fs
on client-side browser *您也不能在客户端浏览器上使用
fs
Instead you get inputs from a browser, and send it to your server (NodeJs), and use fs.writeFile()
on server-side, which is allowed.相反,您从浏览器获取输入,并将其发送到您的服务器(NodeJ),并在服务器端使用
fs.writeFile()
,这是允许的。
What you could do is:你可以做的是:
Electron
to able NodeJs locally to write into local computer.Electron
这样的原生环境来让 NodeJs 在本地写入本地计算机。 What I assume you want to do is 1
我假设你想做的是
1
Is that case you could simply do:在这种情况下你可以简单地做:
function writeAndDownload(str, filename){
let yourContent = str
//Convert your string into ObjectURL
let bom = new Uint8Array([0xef, 0xbb, 0xbf]);
let blob = new Blob([bom, yourContent], { type: "text/plain" });
let url = (window.URL || window.webkitURL).createObjectURL(blob);
//Create a link and assign the ObjectURL
let link = document.createElement("a");
link.style.display = "none";
link.setAttribute("href", url);
link.setAttribute("download", filename);
//Automatically prompt to download
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
}
writeAndDownload("Text you want to save", "savedData")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.