【问题标题】:Gulp: call an async function which provides its own callback from within a transform functionGulp:调用一个异步函数,该函数在转换函数中提供自己的回调
【发布时间】: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


【解决方案1】:

这个问题来自excel 库。 The end event should be finish.

尝试失败

我做了以下,安装修改后的 excel.js:

rm -rf node_modules/excel
git clone https://github.com/bdbosman/excel.js node_modules/excel
cd node_modules/excel && npm i && cd ../..

这还不够,因为excel-as-json 使用的是旧版本的excel

您必须修改excel-as-json 模块,使用excel@1.0.0(合并拉取请求后)或手动编辑node_modules 中的文件。我将在这里描述第二种方式。

临时解决方案

安装模块后编辑excel 文件。

我用过:

sed -i "s/'end'/'finish'/g" node_modules/excel/excelParser.js

然后我跑了:

$ gulp excel-to-jsoncsv
[19:48:21] Using gulpfile ~/so-question-gulp-async-function-call-xlsx/gulpfile.js
[19:48:21] Starting 'excel-to-jsoncsv'...
[19:48:21] Finished 'excel-to-jsoncsv' after 126 ms

而且它显然奏效了。

【讨论】:

    猜你喜欢
    • 2015-01-22
    • 2023-04-04
    • 2012-07-25
    • 2017-11-27
    • 2019-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多