问题
I could implement the export data to csv on node webkit with node fs modules. But now I want to prompt the user to save the file in his/her desired location. Like the download pop-up in case of html. I tried doing on the lines of this code and even this file dialog. Could someone help me find a way out of this. Here's my code.
fs.writeFile("export.csv", data, function(err) {
if(err) {
console.log(err);
} else {
$('#export_file').show();
$('#export_file input').on('change', function (event) {
console.log($(this).val());
console.log("The file was saved!");
});
}
});
<div id="export_file" style="display:none">
<input type="file" nwsaveas nwworkingdir="/data/input/" />
</div>
回答1:
I found a solution here http://9ijy.net/blog/view/6
Step 1 In your html file, add a Input tag block like below:
<input id="export_file" type="file" nwsaveas style="display:none" nwworkingdir=""/>
Step 2 Add a new function in your javascript file like below:
function saveFile(name,data) {
var chooser = document.querySelector(name);
chooser.addEventListener("change", function(evt) {
console.log(this.value); // get your file name
var fs = require('fs');// save it now
fs.writeFile(this.value, data, function(err) {
if(err) {
alert("error"+err);
}
});
}, false);
chooser.click();
}
Step 3 Save your file where ever you like by using saveFile(name,data) function like below:
...
_exportCSV="you data to save";
saveFile('#export_file',_exportCSV);
回答2:
- You are writing the file dialog code as a callback to fs.writeFile. A callback means it will be called AFTER the file is saved. This is what might be happening right now. 1) File is written in the current directory where node-webkit app is running from. 2) When the file is saved without any errors, the dialog shows up. But this dialog is of no help.
- Instead, show the dialog earlier and get the file-path from it(https://github.com/rogerwang/node-webkit/wiki/File-dialogs). Pass this path as the first arg in fs.writeFile(). Done.
来源:https://stackoverflow.com/questions/20609605/node-webkit-export-data-to-csv-and-prompt-the-user-to-save-the-file