如何在我的Grunt構建中驗證CSV文件(編碼,標題,分隔符,列數)?我看了一下CSVLint,但都沒有成功,也不知道如何將它包含在Grunt中。驗證Grunt構建中的CSV文件
編輯:PapaParse看起來很有希望,但沒有Grunt集成。
如何在我的Grunt構建中驗證CSV文件(編碼,標題,分隔符,列數)?我看了一下CSVLint,但都沒有成功,也不知道如何將它包含在Grunt中。驗證Grunt構建中的CSV文件
編輯:PapaParse看起來很有希望,但沒有Grunt集成。
儘管PapaParse的grunt集成不存在,但可以通過在Gruntfile.js
中配置自定義Function Task來利用其API。
通過NPM
安裝papaparse首先,cd
到項目目錄,通過NPM安裝papaparse並將其添加到您的項目package.json
的devDependencies
部分。要做到這一點通過您的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工具中輸入下面的執行:
$咕嚕
注意
運行示例要點通過CLI輸入$ grunt
將處理所有.csv
文件名爲csv
,csv2
和csv3
的目錄。
通過您的CLI運行$ grunt processOneTarget
將只處理名爲csv3
的目錄中的.csv
文件。
由於papaparse.js
利用MultiTask
你會發現,在Gruntfile.js
定義的papaparse
任務包括兩個目標。即setOne
和setTwo
。
setOne
目標src
數組定義到兩個應處理的目錄的路徑。即目錄./csv/
和./csv2
。在這些路徑中找到的所有.csv
文件將使用papaparse.js
中定義的默認papaparse
選項進行處理,因爲目標未定義任何自定義options
。
setTwo
目標src
數組定義到一個目錄的路徑。 (即,例如./csv3/
)。在這個路徑中找到的所有.csv
文件將使用默認的papaparse.js
用,因爲它是設置爲false
的skipEmptyLines
選項之外定義papaparse
選項進行處理。
您可能會發現,只需在Gruntfile.js
中定義一個具有src
陣列中的多個路徑的目標,而無需任何自定義選項即可滿足您的要求。例如:
// ...
grunt.initConfig({
// ...
papaparse: {
myTask: {
src: ['./csv/', './csv2', './csv3']
}
}
// ...
});
// ...
希望這有助於!
好的,謝謝。難道也有可能從grunt.initConfig內的「配置」任務()?例如linting不同的CSV目錄? – Christopher
**更新答:**看起來有通過配置它的方式'grunt.initConfig()' - 參閱修訂_「編輯:更新答案」 _我原來的答覆的部分。 – RobC