How does nw.js open the file selection dialog box and save the file?

  node.js, question

Novice, learn nw.js to develop a markdown editor. Click save button to pop up a file selection dialog box, as follows:

Then the md_editor inside text is saved as an md file. I wrote the following code (in inside, index.html, there is < input type = “file” id = “filedialog” nwsaveas/>):

<script>
 var fs=require("fs");
 var text = $("#md_editor").val();
 $("#save").click(function(){
 var input = $("#fileDialog");
 input.trigger("click");
 var dirr = input.val();
 fs.writeFile(dirr,text,function(err){
 if(err) throw err;
 alert("File Saved!  !"  );
 });
 });
 </script>

This code did not run successfully, because when input.trigger () was executed but the user had not selected the file storage address, the following code had already run, and the value of dirr was null at this time, so fs.writeFile failed to run.

In my other question,@ childeproposal

$("#fileDialog").on("change", function() {
 var dirr = input.val();
 fs.writeFile(dirr,text,function(err){
 if(err) throw err;
 alert("File Saved!  !"  );
 });
 });

There are also some problems. For example, if you save it twice and the location and file name are the same, the change event will not be triggered and the new document will not be saved.

Later, I wondered if I could use the while loop to block input, as shown in line 8 below.

<script>
 var fs=require("fs");
 var text = $("#md_editor").val();
 $("#save").click(function(){
 var input = $("#fileDialog");
 input.trigger("click");
 var dirr = input.val();
 while(dirr=""){dirr=input.val();  bracket
 fs.writeFile(dirr,text,function(err){
 if(err) throw err;
 alert("File Saved!  !"  );
 });
 });
 </script>

However, the nw will be stuck and occupy a large amount of Central Processor and memory in the system. I don’t know where the problem is.

Please teach me how to do it, thanks! !

There are also some problems. For example, if you save it twice and the location and file name are the same, the change event will not be triggered and the new document will not be saved.

I can’t understand why you have encountered this problem.

The logic of the editor when saving files is generally as follows:
1, check whether the new file;

If it is a new file, the path to save the selected file will pop up.
 If it is an old file, overwrite the original file;

The result of the first step is that a file path will definitely be returned.
2. Read the current content of the editor and overwrite the file to the specified path;

Do you have to choose a file path every time you save it?