【问题标题】:How to check if directory exists using Yeoman?如何使用 Yeoman 检查目录是否存在?
【发布时间】:2016-09-28 21:54:12
【问题描述】:

我正在向用户询问目录名称,然后如果该目录存在,我想询问他们是否要归档它。但是我不确定我可以在 Yeoman 中使用什么功能来实现这一点。这是我的代码。

prompting: function () {
    return this.prompt([{
        type: 'input',
        name: 'project_directory',
        message: 'What is the project directory name?'
    }, {
        type: 'confirm',
        name: 'archive',
        message: 'That project already exists. Do you want to archive it?',
        when: function (answers) {
            var destDir = 'project/' + answers.project_directory.replace(/[^0-9a-zA-Z\-.]/g, "").toLowerCase();
            var fso = new ActiveXObject("Scripting.FileSystemObject");

            //Return true if the folder exists
            return (fso.FolderExists(destDir));
        }
    }]).then(function (answers) {


    }.bind(this));
}

【问题讨论】:

    标签: javascript yeoman yeoman-generator


    【解决方案1】:

    Yeoman 不提供任何内置方法来验证文件或目录是否存在。

    但 Yeoman 只是 Node.js,它只是 JavaScript。

    所以你真的想问how to detect if a directory exist with Node

    【讨论】:

      【解决方案2】:

      如果您从 Generator 继承,您将拥有具有 exists() 方法的 this.fs 对象。

      module.exports = class extends Generator {
            /* ... */
        default() {
          this.alreadyCopied = this.fs.exists(this.destination('myfile.txt'));
        }
      }
      

      【讨论】:

        【解决方案3】:

        实际上,正如 Simon Boudrias 所说,Yeoman 并没有为其提供内置方法,但您可以执行以下操作:

        var Generator = require('yeoman-generator');
        var fs = require('fs');
        
        module.exports = class extends Generator{
        
            checkIfFolderExists(){    
        
                fs.stat('YourDirectoryHere'), function(error, stats){            
        
                if(stats!=undefined && stats.isDirectory()){
                   // your directory already exists.          
                }else{
                   // create your directory.
                }
        
                }) ;            
            }         
        }
        

        【讨论】:

          猜你喜欢
          • 2012-09-12
          • 2011-02-15
          • 2023-02-22
          • 2017-07-14
          • 2015-04-29
          • 1970-01-01
          • 2022-07-21
          • 2016-09-20
          相关资源
          最近更新 更多