[英]Is it possible to write data to file using only JavaScript?
我想使用 JavaScript 將數據寫入現有文件。我不想在控制台上打印它。 我想實際將數據寫入abc.txt
。 我讀了很多已回答的問題,但每個問題都在控制台上打印。 在某些地方,他們提供了代碼,但它不起作用。 所以請任何人幫助我如何實際將數據寫入文件。
我引用了代碼但它不起作用:它給出錯誤:
未捕獲的類型錯誤:非法構造函數
在鉻和
SecurityError:操作不安全。
在 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();
}
那么我們真的可以僅使用 Javascript 將數據寫入文件嗎?
您可以使用Blob
和URL.createObjectURL
在瀏覽器中創建文件。 所有最近的瀏覽器都支持這個。
您不能直接保存您創建的文件,因為這會導致大量安全問題,但您可以將其作為下載鏈接提供給用戶。 在支持下載屬性的瀏覽器中,您可以通過鏈接的download
屬性建議文件名。 與任何其他下載一樣,下載文件的用戶將對文件名擁有最終決定權。
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;
};
這是一個使用此技術從textarea
保存任意文本的示例。
如果您想立即啟動下載而不是要求用戶單擊鏈接,則可以使用鼠標事件來模擬鼠標單擊鏈接,就像Lifecube的回答所做的那樣。 我創建了一個使用這種技術的更新示例。
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);
對此的一些建議——
如果您在談論瀏覽器 javascript,出於安全原因,您不能將數據直接寫入本地文件。 HTML 5 新的 API 只能讓你讀取文件。
但是,如果您想寫入數據,並使用戶能夠以文件的形式下載到本地。 以下代碼有效:
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;
}
使用它:
download('the content of the file', 'filename.txt', 'text/plain');
上面的答案很有用,但是我找到了可以幫助您在單擊按鈕時直接下載文本文件的代碼。 在此代碼中,您還可以根據需要更改filename
。 它是帶有 HTML5 的純 javascript 函數。 為我工作!
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();
}
如果無法使用新的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();
在此處查看 Blob 文檔 - Blob MDN以提供文件類型的額外參數。 默認情況下,它將生成 .txt 文件
使用上面用戶 @useless-code ( https://stackoverflow.com/a/21016088/327386 ) 的代碼生成文件。 如果要自動下載文件,請將剛剛生成的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;
}
我在這里找到了很好的答案,但也找到了一種更簡單的方法。
創建 blob 的按鈕和下載鏈接可以組合在一個鏈接中,因為鏈接元素可以具有 onclick 屬性。 (反過來似乎不可能,向按鈕添加 href 不起作用。)
您可以使用bootstrap
將鏈接樣式設置為按鈕,除了樣式之外,它仍然是純 javascript。
將按鈕和下載鏈接結合起來還可以減少代碼,因為需要更少的那些丑陋的getElementById
調用。
此示例只需單擊一個按鈕即可創建文本 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>
這是一個單頁本地文件版本,可在您需要腳本語言的額外處理功能時使用。
代碼:
<!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>
是的,可能這里的代碼是
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.