【发布时间】:2020-03-27 23:04:32
【问题描述】:
我想在 Gulp 中创建一个用于 pipe() 调用的函数,它可以将 xlsx 文件转换为 json。
我使用 NPM 包 'excel-as-json' 为 gulp 3 工作,但是 Gulp 4 迫使我真正理解它在做什么 ;-)
6 小时后,由于缺乏 js/async/streaming 知识,我无法让它工作,这让我很好奇。
代码如下:
paths = {excel_sourcefiles: "./sourcefiles/*.xls*", excel_targetdir_local_csvjson: "./targetfiles_local/*.*"}
var replaceExt = require('replace-ext');
var PluginError = require('plugin-error')
var gulpFunction = require('gulp-function').gulpFunction // default ES6 export
var through = require("through2")
var convertExcel = require('excel-as-json').processFile;
var changed = require('gulp-changed');
var assign = Object.assign || require('object.assign');
var notify = require('gulp-notify');
var gulpIgnore = require('gulp-ignore');
var rename = require('gulp-rename');
gulp.task('excel-to-jsoncsv', function() {
return gulp.src(paths.excel_sourcefiles)
// .pipe(debug())
.pipe(gulpIgnore.exclude("*\~*")) // Ignore temporary files by Excel while xlsx is open
.pipe(gulpIgnore.exclude("*\$*")) // Ignore temporary files by Excel while xlsx is open
.pipe(plumber({errorHandler: notify.onError('gulp-excel-to-jsoncsv error: <%= error.message %>')}))
.pipe(changed(paths.excel_targetdir_local_glob, { extension: '.csv' }))
.pipe(GulpConvertExcelToJson()) // This is where the magic should happen
.pipe(rename({ extname: '.csv' })) // Saving as .csv for SharePoint (does not allow .json files to be saved)
.pipe(gulp.dest(paths.excel_targetdir_local))
});
function GulpConvertExcelToJson() {
return through.obj(function(chunk, enc, callback) {
var self = this
if (chunk.isNull() || chunk.isDirectory()) {
callback() // Do not process directories
// return
}
if (chunk.isStream()) {
callback() // Do not process streams
// return
}
if (chunk.isBuffer()) {
convertExcel(chunk.path, null, null, // Converts file found at `chunk.path` and returns (err, `data`) its callback.
function(err, data) {
if (err) {
callback(new PluginError("Excel-as-json", err))
}
chunk.contents = new Buffer(JSON.stringify(data))
self.push(chunk)
callback()
// return
})
} else {
callback()
}
})
}
我(现在)知道还有其他 excel > json gulp 模块可以让我在不编写自己的模块的情况下解决这个问题,但我想了解我应该在这里做些什么不同。
返回的错误是“您是否忘记发出异步完成信号?”,我试图不这样做。但是,可能我尝试使用 var self = this 修复错误“this.push is not a function”并不是我应该做的。
查看 gulp-zip 之类的示例向我介绍了不熟悉的符号,使我无法自学摆脱这种情况。
总结:
- 我将如何在 through.obj 函数调用期间调用异步函数,其中块的内容使用(不受我控制的)异步函数更新,该函数只为我提供回调(错误,数据)?
【问题讨论】:
-
我认为如果你能用它创建一个 repo 并与我们分享它会有所帮助。这将使调试变得更简单。
-
excel-as-json 还在工作吗?它是为 npm2 编写的。当我运行它时,它并没有真正做任何事情。 convertExcel('cols.xlsx', 'rows.csv', {}, (err, data) => { console.log(data) })
-
@MattV 就像 Aniket 提到的,
excel-as-json必须更新,但我回答了一个解决方法。如果你想一起做,请给我发私信。
标签: javascript node.js asynchronous callback gulp