2014-06-08 29 views
0

我已經經歷了很多的教程,我永遠無法得到這個工作:節點的Webkit如何將div的值保存爲txt文件

我要救一個div的內容(啓用contenteditable)到帶有節點webkit的.txt文件。這部分看起來是這樣的:

<div id="editor" class="textbox" contenteditable></div> 

和我有輸入字段,可以讓我選擇文件:

<input type="file" nwsaveas="untitled.txt" style="display:none;"/> 

但是我無法找到如何保存的價值的任何資源編輯器div作爲用戶計算機上的.txt文件。

我想這TUTS加教程簡要說明它但它似乎沒有當我試圖在我自己的項目工作:http://code.tutsplus.com/tutorials/introduction-to-html5-desktop-apps-with-node-webkit--net-36296

有誰知道我能做到這一點?

回答

1

你必須讓文件對話框,模擬click事件的input的開放,然後得到的#editorinnerHTML,最後使用節點的fs.writeFile保存的內容。

這裏充滿工作示例:

<!DOCTYPE html> 
<html> 
<head> 
<script> 
var initInputFile = function() { 
    document.getElementById('inputFile').addEventListener('change', function() { 
     var path = this.value; //get fullpath of chosen file 
     var content = document.getElementById('editor').innerHTML; //get editor's content 
     content = (' ' + content).slice(1); //hack to prevent strange bug of saving just half of the content 
     require('fs').writeFile(path, content, function(err) { 
      if (err) throw err; 
      console.log('done'); 
     }); 

     var wrapper = document.getElementById('inputFileWrapper'); 
     wrapper.innerHTML = wrapper.innerHTML; //hack to make "change" event trigger... 
     initInputFile();       //...when choosing the same file 
    }); 
} 
window.onload = function() { 
    initInputFile(); 
    document.getElementById('saveBtn').addEventListener('click', function() { 
     var event = document.createEvent('MouseEvents'); 
     event.initMouseEvent('click'); 
     document.getElementById('inputFile').dispatchEvent(event); 
    }); 
} 
</script> 
</head> 
<body> 

    <div id="editor" class="textbox" style="width:400px; height:100px;" contenteditable></div> 
    <div id="inputFileWrapper" style="display:none;"> 
     <input type="file" id="inputFile" nwsaveas="untitled.txt"/> 
    </div> 
    <input type="button" id="saveBtn" value="Save" /> 

</body> 
</html> 

希望這有助於。

相關問題