2017-05-08 55 views

回答

2

尽管PapaParse的grunt集成不存在,但可以通过在Gruntfile.js中配置自定义Function Task来利用其API。


通过NPM

安装papaparse首先,cd到项目目录,通过NPM安装papaparse并将其添加到您的项目package.jsondevDependencies部分。要做到这一点通过您的CLI工具运行以下命令:

$ npm i -D papaparse


Gruntfile.js

下面的要点说明了如何配置一个自定义函数任务在Gruntfile.js命名validateCSV

module.exports = function(grunt) { 

    // Requirements 
    var fs = require('fs'); 
    var Papa = require('papaparse'); 

    // Other project configuration tasks. 
    grunt.initConfig({ 
     // ... 
    }); 

    /** 
    * Register a custom Function task to validate .csv files using Papa Parse. 
    */ 
    grunt.registerTask('validateCSV', 'Lint .csv files via Papa Parse', function() { 

     var glob = './csv/*.csv'; // <-- Note: Edit glob pattern as required. 

     var success = true; 

     // Create an Array of all .csv files using the glob pattern provided. 
     var csvFiles = grunt.file.expand(glob).map(function(file) { 
      return file; 
     }); 

     // Report if no .csv files were found and return early. 
     if (csvFiles.length === 0) { 
      grunt.log.write('No .csv files were found'); 
      return; 
     } 

     // Loop over each .csv file in the csvFiles Array. 
     csvFiles.forEach(function(csvFile) { 

      // Read the contents of the .csv file. 
      var csvString = fs.readFileSync(csvFile, { 
       encoding: 'utf8' 
      }); 

      // Parse the .csv contents via Papa Parse. 
      var papa = Papa.parse(csvString, { 
       delimiter: ',', 
       newline: '', 
       quoteChar: '"', 
       header: true, 
       skipEmptyLines: true 

       // For additional config options visit: 
       // http://papaparse.com/docs#config 
      }); 

      // Basic error and success logging. 
      if (papa.errors.length > 0) { 
       grunt.log.error('Error(s) in file: '['red'] + csvFile['red']); 

       // Report each error for a single .csv file. 
       // For additional Papa Parse errors visit: 
       // http://papaparse.com/docs#errors 
       papa.errors.forEach(function(error) { 
        grunt.log.write('\n type: ' + error.type); 
        grunt.log.write('\n code: ' + error.code); 
        grunt.log.write('\n message: ' + error.message); 
        grunt.log.write('\n row: ' + error.row + '\n\n'); 
       }); 

       // Indicate that a .csv file failed validation. 
       success = false; 

      } else { 
       grunt.log.ok('No errors found in file: ' + csvFile); 
      } 
     }); 

     // If errors are found in any of the .csv files this will 
     // prevent subsequent defined tasks from being processed. 
     if (!success) { 
      grunt.fail.warn('Errors(s) were found when validating .csv files'); 
     } 
    }); 

    // Register the custom Function task. 
    grunt.registerTask('default', [ 
     'validateCSV' 
     // ... 
    ]); 

}; 

注意

的代码(从上面的Gruntfile.js拍摄)下面这行,上面写着:

var glob = './csv/*.csv'; 

...将需要改变/根据项目编辑要求。目前globbing pattern假定所有.csv文件都驻留在名为csv的文件夹中。

可能也需要根据您的要求设置config选项。

自定义功能任务还包括一些基本的错误和成功报告,将记录到CLI。


运行任务

运行繁重的任务只是执行通过您的CLI工具如下:

$ grunt validateCSV


编辑:更新答案(根据以下评论...)

难道也有可能“配置”,从 grunt.initConfig()内完成这项任务?例如linting不同的CSV目录?

要实现这一点,您可以创建一个单独的Javascript模块,输出一个Registered MutliTask

让我们把它叫做papaparse.js,并将其保存到一个名为custom-grunt-tasks驻留在同一顶层目录为您Gruntfile.js

注目录:该.js文件和目录名可以是你喜欢的任何名称,但您将需要更新Gruntfile.js内的参考文献。

papaparse.js

module.exports = function(grunt) { 

    'use strict'; 

    // Requirements 
    var fs = require('fs'); 
    var Papa = require('papaparse'); 

    grunt.registerMultiTask('papaparse', 'Misc Tasks', function() { 

     // Default options. These are used when no options are 
     // provided via the initConfig({...}) papaparse task. 
     var options = this.options({ 
      quotes: false, 
      delimiter: ',', 
      newline: '', 
      quoteChar: '"', 
      header: true, 
      skipEmptyLines: true 
     }); 

     // Loop over each path provided via the src array. 
     this.data.src.forEach(function(dir) { 

      // Append a forward slash If a directory path 
      // provided does not end in with one. 
      if (dir.slice(-1) !== '/') { 
       dir += '/'; 
      } 

      // Generate the globbin pattern. 
      var glob = [dir, '*.csv'].join(''); 

      // Create an Array of all .csv files using the glob pattern. 
      var csvFiles = grunt.file.expand(glob).map(function(file) { 
       return file; 
      }); 

      // Report if no .csv files were found and return early. 
      if (csvFiles.length === 0) { 
       grunt.log.write(
        '>> No .csv files found using the globbing '['yellow'] + 
        'pattern: '['yellow'] + glob['yellow'] 
       ); 
       return; 
      } 

      // Loop over each .csv file in the csvFiles Array. 
      csvFiles.forEach(function(csvFile) { 

       var success = true; 

       // Read the contents of the .csv file. 
       var csvString = fs.readFileSync(csvFile, { 
        encoding: 'utf8' 
       }); 

       // Parse the .csv contents via Papa Parse. 
       var papa = Papa.parse(csvString, options); 

       // Basic error and success logging. 
       if (papa.errors.length > 0) { 
        grunt.log.error('Error(s) in file: '['red'] + csvFile['red']); 

        // Report each error for a single .csv file. 
        // For additional Papa Parse errors visit: 
        // http://papaparse.com/docs#errors 
        papa.errors.forEach(function(error) { 
         grunt.log.write('\n type: ' + error.type); 
         grunt.log.write('\n code: ' + error.code); 
         grunt.log.write('\n message: ' + error.message); 
         grunt.log.write('\n row: ' + error.row + '\n\n'); 
        }); 

        // Indicate that a .csv file failed validation. 
        success = false; 

       } else { 
        grunt.log.ok('No errors found in file: ' + csvFile); 
       } 

       // If errors are found in any of the .csv files this will prevent 
       // subsequent files and defined tasks from being processed. 
       if (!success) { 
        grunt.fail.warn('Errors(s) found when validating .csv files'); 
       } 
      }); 

     }); 
    }); 
}; 

Gruntfile.js

你那么Gruntfile.js可以配置是这样的:

module.exports = function(grunt) { 

    grunt.initConfig({ 
     // ... 
     papaparse: { 
      setOne: { 
       src: ['./csv/', './csv2'] 
      }, 
      setTwo: { 
       src: ['./csv3/'], 
       options: { 
        skipEmptyLines: false 
       } 
      } 
     } 

    }); 

    // Load the custom multiTask named `papaparse` - which is defined in 
    // `papaparse.js` stored in the directory named `custom-grunt-tasks`. 
    grunt.loadTasks('./custom-grunt-tasks'); 

    // Register and add papaparse to the default Task. 
    grunt.registerTask('default', [ 
     'papaparse' // <-- This runs Targets named setOne and setTwo 
     // ... 
    ]); 

    // `papaparse.js` allows for multiple targets to be defined, so 
    // you can use the colon notation to just run one Target. 
    // The following only runs the setTwo Target. 
    grunt.registerTask('processOneTarget', [ 
     'papaparse:setTwo' 
     // ... 
    ]); 

}; 

运行任务

papaparse任务已添加到taskList阵列的default任务,所以它可以通过您的CLI工具中输入下面的执行:

$咕噜

注意

  1. 运行示例要点通过CLI输入$ grunt将处理所有.csv文件名为csvcsv2csv3的目录。

  2. 通过您的CLI运行$ grunt processOneTarget将只处理名为csv3的目录中的.csv文件。

  3. 由于papaparse.js利用MultiTask你会发现,在Gruntfile.js定义的papaparse任务包括两个目标。即setOnesetTwo

  4. setOne目标src数组定义到两个应处理的目录的路径。即目录./csv/./csv2。在这些路径中找到的所有.csv文件将使用papaparse.js中定义的默认papaparse选项进行处理,因为目标未定义任何自定义options

  5. setTwo目标src数组定义到一个目录的路径。 (即,例如./csv3/)。在这个路径中找到的所有.csv文件将使用默认的papaparse.js用,因为它是设置为falseskipEmptyLines选项之外定义papaparse选项进行处理。

  6. 您可能会发现,只需在Gruntfile.js中定义一个具有src阵列中的多个路径的目标,而无需任何自定义选项即可满足您的要求。例如:

// ... 
    grunt.initConfig({ 
     // ... 
     papaparse: { 
      myTask: { 
       src: ['./csv/', './csv2', './csv3'] 
      } 
     } 
     // ... 
    }); 
// ... 

希望这有助于!

+0

好的,谢谢。难道也有可能从grunt.initConfig内的“配置”任务()?例如linting不同的CSV目录? – Christopher

+0

**更新答:**看起来有通过配置它的方式'grunt.initConfig()' - 参阅修订_“编辑:更新答案” _我原来的答复的部分。 – RobC