I cut gulpfile.js into several files. My purpose is to share the data with various tasks. And I use windows system, gulp 5 and "type": "module" config.
The file structure is given below:
gulpfile.js
tasks/clean.js
tasks/deploy_data.js
data/path.js
data/other.js
gulpfile.js
import gulp from 'gulp';
import clean from './tasks/clean.js';
import deploy_data from './data/deploy_data.js';
global.data = {}; // share data with all tasks.
function deploy_at_start() {
gulp.series(deploy_data);
}
deploy_at_start(); // I hope that deploy_data will be executed before any task I debug, because each task needs to use the contents of data.
console.log(data); // {} Blank, obviously deploy_data has not been completed yet, I want the code below to be executed only after it completes.
export {
clean,
// alot of other tasks
};
./tasks/clean.js
function clean(cb) {
console.log(data.path.src); // I need to get some information from data, such as the path I want to delete.
cb();
}
export default clean;
The point is this
data/path.js
const path = {
src: './folder/*',
};
export default path;
tasks/deploy_data.js
import path from 'node:path';
import { pathToFileURL } from 'node:url';
async function deploy_data(cb) {
const dir = path.join(process.cwd(), 'data');
const files = fs
.readdirSync(dir, { withFileTypes: true }).filter((item) => item.isFile())
.map((item) => item.name); // I have a lot of data files, so this is the easier way to get all the data
for (const file of files) {
data[path.parse(file).name] = (await import(pathToFileURL(path.join(dir, file)).href)).default;
}
cb();
}
export default deploy_data;
When I execute gulp clean, I can't get the data.path
information. I think it may be because deploy_data
is async and something went wrong.
From the terminal, I can see that deploy_data
completes its work after clean is completed, which is why data is empty.
I understand that I can use gulp.series to execute deploy_data before clean, but I have a huge amount of data. I think I can achieve the goal by executing deploy_data once at the beginning of gulpfile.js
similar to the current method.
In the above case, is there a way for me to execute deploy_data before executing any gulp task (the task that has been exported) and wait for it to complete before executing other code?
Just add a top-level await
:
await deploy_at_start();
and don't forget to return from deploy_at_start
so await
would wait gulp.series()
to finish:
function deploy_at_start() {
return gulp.series(deploy_data);
}