search

Home  >  Q&A  >  body text

node.js - nw.js怎么打开文件选择对话框,并保存文件?

新手,学习nw.js开发一款markdown编辑器,想要实现点击save按钮就弹出文件选择对话框,如下:

然后把md_editor里文字保存成md文件。我写的代码如下(在index.html里有<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>

这段代码运行不成功,原因在于当input.trigger()执行但是用户还没有选择好文件保存地址时,后面代码已经运行,这时dirr的值是空值,所以fs.writeFile运行失败。

在我的另一个问题中,@公子 建议

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

也有一些问题,比如如果保存两次,且保存位置、文件名一样,那么就不会触发change事件,也就不会保存新文档了。

后来我就又想能不能用while循环来阻塞input,如下第八行:

<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();}
        fs.writeFile(dirr,text,function(err){
            if(err) throw err;
            alert("File Saved!!");
        });
    });
    </script>

但是这样nw整个都会卡死,并占用系统大量的cpu和内存。不知道问题出在哪里。

请对nw文件模块比较熟悉的各位教教我怎么做,谢谢!!

巴扎黑巴扎黑2786 days ago822

reply all(2)I'll reply

  • PHP中文网

    PHP中文网2017-04-17 13:19:41

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

    Indicates that you can’t understand why you encounter this problem?

    The logic of the editor when saving a file is generally as follows:
    1. Check whether it is a new 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 in the specified path;

    Do you have to select the file path every time you save?

    reply
    0
  • 黄舟

    黄舟2017-04-17 13:19:41

    Read the document carefully. I think what you did before is not doing your job properly. The correct thing is to respond to the save event of filedialog

    reply
    0
  • Cancelreply