[英]Is it possible to write data to file using only JavaScript?
I want to Write Data to existing file using JavaScript. I don't want to print it on console.我想使用 JavaScript 将数据写入现有文件。我不想在控制台上打印它。 I want to Actually Write data to abc.txt
.我想实际将数据写入abc.txt
。 I read many answered question but every where they are printing on console.我读了很多已回答的问题,但每个问题都在控制台上打印。 at some place they have given code but its not working.在某些地方,他们提供了代码,但它不起作用。 So please can any one help me How to actually write data to File.所以请任何人帮助我如何实际将数据写入文件。
I referred the code but its not working: its giving error:我引用了代码但它不起作用:它给出错误:
Uncaught TypeError: Illegal constructor未捕获的类型错误:非法构造函数
on chrome and在铬和
SecurityError: The operation is insecure. SecurityError:操作不安全。
on Mozilla在 Mozilla 上
var f = "sometextfile.txt";
writeTextFile(f, "Spoon")
writeTextFile(f, "Cheese monkey")
writeTextFile(f, "Onion")
function writeTextFile(afilename, output)
{
var txtFile =new File(afilename);
txtFile.writeln(output);
txtFile.close();
}
So can we actually write data to file using only Javascript or NOT?那么我们真的可以仅使用 Javascript 将数据写入文件吗?
You can create files in browser using Blob
and URL.createObjectURL
.您可以使用Blob
和URL.createObjectURL
在浏览器中创建文件。 All recent browsers support this .所有最近的浏览器都支持这个。
You can not directly save the file you create, since that would cause massive security problems, but you can provide it as a download link for the user.您不能直接保存您创建的文件,因为这会导致大量安全问题,但您可以将其作为下载链接提供给用户。 You can suggest a file name via the download
attribute of the link, in browsers that support the download attribute.在支持下载属性的浏览器中,您可以通过链接的download
属性建议文件名。 As with any other download, the user downloading the file will have the final say on the file name though.与任何其他下载一样,下载文件的用户将对文件名拥有最终决定权。
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
// returns a URL you can use as a href
return textFile;
};
Here's an example that uses this technique to save arbitrary text from a textarea
.这是一个使用此技术从textarea
保存任意文本的示例。
If you want to immediately initiate the download instead of requiring the user to click on a link, you can use mouse events to simulate a mouse click on the link as Lifecube 's answer did.如果您想立即启动下载而不是要求用户单击链接,则可以使用鼠标事件来模拟鼠标单击链接,就像Lifecube的回答所做的那样。 I've created an updated example that uses this technique.我创建了一个使用这种技术的更新示例。
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.createElement('a');
link.setAttribute('download', 'info.txt');
link.href = makeTextFile(textbox.value);
document.body.appendChild(link);
// wait for the link to be added to the document
window.requestAnimationFrame(function () {
var event = new MouseEvent('click');
link.dispatchEvent(event);
document.body.removeChild(link);
});
}, false);
Some suggestions for this -对此的一些建议——
If you are talking about browser javascript, you can not write data directly to local file for security reason.如果您在谈论浏览器 javascript,出于安全原因,您不能将数据直接写入本地文件。 HTML 5 new API can only allow you to read files. HTML 5 新的 API 只能让你读取文件。
But if you want to write data, and enable user to download as a file to local.但是,如果您想写入数据,并使用户能够以文件的形式下载到本地。 the following code works:以下代码有效:
function download(strData, strFileName, strMimeType) {
var D = document,
A = arguments,
a = D.createElement("a"),
d = A[0],
n = A[1],
t = A[2] || "text/plain";
//build download link:
a.href = "data:" + strMimeType + "charset=utf-8," + escape(strData);
if (window.MSBlobBuilder) { // IE10
var bb = new MSBlobBuilder();
bb.append(strData);
return navigator.msSaveBlob(bb, strFileName);
} /* end if(window.MSBlobBuilder) */
if ('download' in a) { //FF20, CH19
a.setAttribute("download", n);
a.innerHTML = "downloading...";
D.body.appendChild(a);
setTimeout(function() {
var e = D.createEvent("MouseEvents");
e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
D.body.removeChild(a);
}, 66);
return true;
}; /* end if('download' in a) */
//do iframe dataURL download: (older W3)
var f = D.createElement("iframe");
D.body.appendChild(f);
f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData);
setTimeout(function() {
D.body.removeChild(f);
}, 333);
return true;
}
to use it:使用它:
download('the content of the file', 'filename.txt', 'text/plain');
Try尝试
let a = document.createElement('a'); a.href = "data:application/octet-stream,"+encodeURIComponent("My DATA"); a.download = 'abc.txt'; a.click();
If you want to download binary data look here如果你想下载二进制数据看这里
2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop works (reason: sandbox security restrictions) - but JSFiddle version works - here 2020.06.14 我将 Chrome 升级到 83.0 及更高版本 SO 代码段停止工作(原因:沙盒安全限制) - 但 JSFiddle 版本工作 -在这里
Above answer is useful but, I found code which helps you to download text file directly on button click.上面的答案很有用,但是我找到了可以帮助您在单击按钮时直接下载文本文件的代码。 In this code you can also change filename
as you wish.在此代码中,您还可以根据需要更改filename
。 It's pure javascript function with HTML5.它是带有 HTML5 的纯 javascript 函数。 Works for me!为我工作!
function saveTextAsFile()
{
var textToWrite = document.getElementById("inputTextToSave").value;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else
{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
In the case it is not possibile to use the new Blob
solution, that is for sure the best solution in modern browser, it is still possible to use this simpler approach, that has a limit in the file size by the way:如果无法使用新的Blob
解决方案,这肯定是现代浏览器中的最佳解决方案,仍然可以使用这种更简单的方法,顺便说一下文件大小有限制:
function download() {
var fileContents=JSON.stringify(jsonObject, null, 2);
var fileName= "data.json";
var pp = document.createElement('a');
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
pp.setAttribute('download', fileName);
pp.click();
}
setTimeout(function() {download()}, 500);
$('#download').on("click", function() { function download() { var jsonObject = { "name": "John", "age": 31, "city": "New York" }; var fileContents = JSON.stringify(jsonObject, null, 2); var fileName = "data.json"; var pp = document.createElement('a'); pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents)); pp.setAttribute('download', fileName); pp.click(); } setTimeout(function() { download() }, 500); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="download">Download me</button>
const data = {name: 'Ronn', age: 27}; //sample json
const a = document.createElement('a');
const blob = new Blob([JSON.stringify(data)]);
a.href = URL.createObjectURL(blob);
a.download = 'sample-profile'; //filename to download
a.click();
Check Blob documentation here - Blob MDN to provide extra parameters for file type.在此处查看 Blob 文档 - Blob MDN以提供文件类型的额外参数。 By default it will make .txt file默认情况下,它将生成 .txt 文件
Use the code by the user @useless-code above ( https://stackoverflow.com/a/21016088/327386 ) to generate the file.使用上面用户 @useless-code ( https://stackoverflow.com/a/21016088/327386 ) 的代码生成文件。 If you want to download the file automatically, pass the textFile
that was just generated to this function:如果要自动下载文件,请将刚刚生成的textFile
传递给此函数:
var downloadFile = function downloadURL(url) {
var hiddenIFrameID = 'hiddenDownloader',
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = url;
}
I found good answers here, but also found a simpler way.我在这里找到了很好的答案,但也找到了一种更简单的方法。
The button to create the blob and the download link can be combined in one link, as the link element can have an onclick attribute.创建 blob 的按钮和下载链接可以组合在一个链接中,因为链接元素可以具有 onclick 属性。 (The reverse seems not possible, adding a href to a button does not work.) (反过来似乎不可能,向按钮添加 href 不起作用。)
You can style the link as a button using bootstrap
, which is still pure javascript, except for styling.您可以使用bootstrap
将链接样式设置为按钮,除了样式之外,它仍然是纯 javascript。
Combining the button and the download link also reduces code, as fewer of those ugly getElementById
calls are needed.将按钮和下载链接结合起来还可以减少代码,因为需要更少的那些丑陋的getElementById
调用。
This example needs only one button click to create the text-blob and download it:此示例只需单击一个按钮即可创建文本 blob 并下载它:
<a id="a_btn_writetofile" download="info.txt" href="#" class="btn btn-primary"
onclick="exportFile('This is some dummy data.\nAnd some more dummy data.\n', 'a_btn_writetofile')"
>
Write To File
</a>
<script>
// URL pointing to the Blob with the file contents
var objUrl = null;
// create the blob with file content, and attach the URL to the downloadlink;
// NB: link must have the download attribute
// this method can go to your library
function exportFile(fileContent, downloadLinkId) {
// revoke the old object URL to avoid memory leaks.
if (objUrl !== null) {
window.URL.revokeObjectURL(objUrl);
}
// create the object that contains the file data and that can be referred to with a URL
var data = new Blob([fileContent], { type: 'text/plain' });
objUrl = window.URL.createObjectURL(data);
// attach the object to the download link (styled as button)
var downloadLinkButton = document.getElementById(downloadLinkId);
downloadLinkButton.href = objUrl;
};
</script>
Here is a single-page local-file version for use when you need the extra processing functionality of a scripting language.这是一个单页本地文件版本,可在您需要脚本语言的额外处理功能时使用。
Code:代码:
<!DOCTYPE HTML>
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT>
// do text manipulation here
let string1 = 'test\r\n';
let string2 = 'export.';
// assemble final string
const finalText = string1 + string2;
// convert to blob
const data = new Blob([finalText], {type: 'text/plain'});
// create file link
const link = document.createElement('a');
link.innerHTML = 'download';
link.setAttribute('download', 'data.txt');
link.href = window.URL.createObjectURL(data);
document.body.appendChild(link);
// preview the output in a paragraph
const htmlBreak = string => {
return string.replace(/(?:\r\n|\r|\n)/g, '<br>');
}
const preview = document.createElement('p');
preview.innerHTML = htmlBreak(finalText);
preview.style.border = "1px solid black";
document.body.appendChild(preview);
</SCRIPT>
</BODY>
</HTML>
Yes its possible Here the code is是的,可能这里的代码是
const fs = require('fs') let data = "Learning how to write in a file." fs.writeFile('Output.txt', data, (err) => { // In case of a error throw err. if (err) throw err; })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.