你必須讓文件對話框,模擬click
事件的input
的開放,然後得到的#editor
innerHTML
,最後使用節點的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>
希望這有助於。