惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

大猫的无限游戏
大猫的无限游戏
K
Kaspersky official blog
Apple Machine Learning Research
Apple Machine Learning Research
B
Blog
aimingoo的专栏
aimingoo的专栏
M
MIT News - Artificial intelligence
小众软件
小众软件
云风的 BLOG
云风的 BLOG
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Hugging Face - Blog
Hugging Face - Blog
S
SegmentFault 最新的问题
Stack Overflow Blog
Stack Overflow Blog
量子位
S
Secure Thoughts
G
GRAHAM CLULEY
C
CXSECURITY Database RSS Feed - CXSecurity.com
人人都是产品经理
人人都是产品经理
雷峰网
雷峰网
T
Threat Research - Cisco Blogs
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
Cisco Talos Blog
Cisco Talos Blog
G
Google Developers Blog
爱范儿
爱范儿
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
有赞技术团队
有赞技术团队
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Martin Fowler
Martin Fowler
The GitHub Blog
The GitHub Blog
Google DeepMind News
Google DeepMind News
C
Cisco Blogs
D
Darknet – Hacking Tools, Hacker News & Cyber Security
博客园 - 聂微东
宝玉的分享
宝玉的分享
H
Hackread – Cybersecurity News, Data Breaches, AI and More
N
Netflix TechBlog - Medium
Forbes - Security
Forbes - Security
Engineering at Meta
Engineering at Meta
S
Security Affairs
Help Net Security
Help Net Security
博客园 - 三生石上(FineUI控件)
AWS News Blog
AWS News Blog
博客园 - 叶小钗
Recent Commits to openclaw:main
Recent Commits to openclaw:main
V2EX - 技术
V2EX - 技术
Hacker News: Ask HN
Hacker News: Ask HN
Project Zero
Project Zero
H
Heimdal Security Blog
W
WeLiveSecurity
C
Check Point Blog

oida.dev | TypeScript, Rust

TypeScript's `erasableSyntaxOnly` Flag Unsafe for work Tokio: Macros Tokio: Channels Tokio: Getting Started Network Applications on the Tokio Stack Remake, Remodel, Reduce. The `never` type and error handling in TypeScript 5 Inconvenient Truths about TypeScript Refactoring in Rust: Introducing Traits Refactoring in Rust: Abstraction with the Newtype Pattern Announcing the TypeScript Cookbook TypeScript: Iterating over objects The road to universal JavaScript 10 years of oida.dev Rust: Tiny little traits The TypeScript converging point How not to learn TypeScript Getting started with Rust Introducing Slides and Coverage TypeScript: The humble function overload TypeScript + React: Children types are broken TypeScript: In defense of any Rust: Enums to wrap multiple errors Dissecting Deno Error handling in Rust TypeScript: Unexpected intersections Upgrading Node.js dependencies after a yarn audit TypeScript: Array.includes on narrow types TypeScript + React: Typing Generic forwardRefs shared, util, core: Schroedinger's module names Learning Rust and Go TypeScript: Narrow types in catch clauses TypeScript: Low maintenance types Tidy TypeScript: Name your generics Tidy TypeScript: Avoid traditional OOP patterns Tidy TypeScript: Prefer type aliases over interfaces Tidy TypeScript: Prefer union types over enums My new book: TypeScript in 50 Lessons Go Preact! ❤️ this in JavaScript and TypeScript TypeScript and ECMAScript Modules TypeScript + React: Why I don't use React.FC TypeScript + React: Component patterns TypeScript: Augmenting global and lib.dom.d.ts Vite with Preact and TypeScript TypeScript: Union to intersection type 11ty: Generate Twitter cards automatically Are large node module dependencies an issue? TypeScript: Variadic Tuple Types Preview TypeScript: Improving Object.keys Remake, Remodel. Part 4. TypeScript + React: Typing custom hooks with tuple types TypeScript: Assertion signatures and Object.defineProperty TypeScript: Check for object properties and narrow down type Boolean in JavaScript and TypeScript void in JavaScript and TypeScript Symbols in JavaScript and TypeScript Why I use TypeScript TypeScript + React: Extending JSX Elements TypeScript: Validate mapped types and const context TypeScript: Match the exact object shape TypeScript: The constructor interface pattern Streaming your Meetup - Part 4: Directing and Streaming with OBS Streaming your Meetup - Part 3: Speaker audio Streaming your Meetup - Part 2: Speaker video Streaming your Meetup - Part 1: Basics and Projector TypeScript and React Guide: Added a new styles chapter TypeScript and React Guide: Added a new render props chapter TypeScript and React: Styles and CSS TypeScript and React TypeScript and React Guide: Added a new prop types chapter TypeScript without TypeScript -- JSDoc superpowers TypeScript: Mapped types for type maps JAMStack vs serverless web apps The Unsung Benefits of JAMStack Sites TypeScript: Ambient modules for Webpack loaders My most favourite talks in 2018 TypeScript and React Guide: Added a new context chapter TypeScript: Built-in generic types TypeScript: Type predicates JSX is syntactic sugar TypeScript and React Guide: Added a new hooks chapter Getting your CfP application right FAQ on our Angular Connect Talk: Automating UI development TypeScript and Substitutability Debugging Node.js apps in TypeScript with Visual Studio Code From Medium: Deconfusing Pre- and Post-processing From Medium: PostCSS misconceptions Saving and scraping a website with Puppeteer Cutting the mustard - 2018 edition Wordpress as CMS for your JAMStack sites My most favourite podcast episodes in 2017 My most favourite talks in 2017 My most favourite books in 2017 The Best Request Is No Request, Revisited Not so hidden figures - Organizing ScriptConf My podcast journey to ScriptCast Grid layout, grid layout everywhere! #scriptconf and #devone
Gulp and Promises
2015-12-21 · via oida.dev | TypeScript, Rust

The Gulp task system does not only work with streams alone, but also with other asynchronous patterns. One of those are well known Promises! Find out how we can use two Promise-based tools to create a thorough file sync between two folders.

File sync: Copy new files to a destination #

Think of a build system where you store your files in a source directory, but have every computation done in a working or build directory. Gradle for instance is one of those tools that recommend you to work this way. And for good reason: You never touch the source, making it more robust to integrate in CI environments. A pull from master doesn’t kill your intermediates. And on the other: Your intermediates or results don’t interfere with everything new coming from your Git branch.

So, what we are aiming for is a call that copies all the files from a source directory to a destination directory, where Gulp awaits to execute your build tasks. With the concepts we learned from incremental builds we are able to create the first part: Copying new files from a source to a destination:

var globArray = [ ... ]  // all the files you want to read

gulp.task('copy-src', function(){
return gulp.src(globArray, { cwd: '../../src/' })
.pipe(newer('.'))
.pipe(gulp.dest('.'));
});

That takes care of all the new files or changed files, without copying anything that doesn’t need to be there. That’s half the battle. What about the files that have been copied from a previous run, but then got removed? If you really want to have a direct copy of your source directory, you also want to remove them in your destination directory.

Getting the diff between two directories #

To get the difference between the source and destination directory we have several possibilities, even Gulp plugins to use. However, most of them feel kind of clumsy or “do too much”, something that a Gulp plugin should never do.

So, why not do it on our own? Here’s the plan:

  • Read both source and destination directory.
  • Compare both lists and find the difference
  • Delete the files that are left, hence: The ones that are not in the source directory anymore.

We have some Promised-based Node modules for that:

  • globby: Creates a list of file paths based on a glob. Something very similar to Gulp.s
  • del: A module that deletes files based on a glob. This is actually the preferred way by Gulp to take care of deleting files.

And here’s how we are going to combine them:

gulp.task('diff', function() {
return Promise.all([ /* 1 */
globby(globArray, { nodir: true }), /* 2 */
globby(globArray, { cwd: '../../src/', nodir: true }) /* 3 */
]).then(function(paths) {
return paths[0].filter(function(i) { /* 4 */
return paths[1].indexOf(i) < 0;
});
}).then(function(diffs) { /* 5 */
return del(diffs);
});
});

Let’s go through this one by one.

  1. We use Promise.all to run two Promise-based glob calls against our file system.
  2. globby by the one and only Sindre Sorhus allows for Gulp-style globbing (including directories) with Promises. Add the nodir parameter to the globby call to not get directory file handles.
  3. Do the same for the source directory. We change the working directory to our source directory. By using the cwd parameter, the file list has the same structure as from the first globby call. Since we run both Promises with Promise.all, we also get an array of results.
  4. The array of results contain two arrays of file names. The first one from the destination, the second one from our source. We use the Array.prototype.filter and Array.prototype.indexOf function to compare our results: We filter all elements that are not in our second array. Note: This procedure might take some time depending on how many file paths you are going to compare. We are talking seconds here. This is quite some time in the Gulp world.
  5. The result of this step is an array with “leftovers”: All those files that have been removed from the source directory but still exist in our working directory. We use Sindre Sorhus’ del module that takes care of this files. It returns also a Promise, so it’s perfectly usable with the Promise-chain that we made here.

ES6 fat arrows #

It’s even more beautiful when you work with ES6 fat arrow functions:

gulp.task('diff', function() {
return Promise.all([
globby(globArray, { nodir: true }),
globby(globArray, { cwd: '../../src/', nodir: true })
])
.then(paths => paths[0].filter(i => paths[1].indexOf(i) < 0))
.then(diffs => del(diffs))
});

Nice, clean and totally in tune with Gulp!

Bottom line #

With Gulp you have a vast ecosystem of plugins at your hand. This ecosystem expands as you can use any stream related tool and wrap it around the Gulp API. But you are not bound to streams alone. With Promises, any asynchronous code can work with the Gulp task system! So the amount of tools to choose from grows even more!

Software used: #

Works with both Gulp 3 and Gulp 4. The rest is Node.js native.

Related Articles