[Node.js] process.nextTick for converting sync to async
For example we have a function to check the filesize:
const fs = require('fs'); function fileSize (fileName, cb) { if (typeof fileName !== 'string') { throw new TypeError('filename should be string') } fs.stat(fileName, (err, stats) => { if (err) { return cb(err) } cb(null, stats.size); }); } fileSize(__filename, (err, size) => { if (err) throw err; console.log(`Size in KB: ${size/1024}`); }); console.log('Hello!'); /* Hello! Size in KB: 0.44921875 */
It works fine, but the 'fileSize' function has a problem,
if (typeof fileName !== 'string') { return new TypeError('filename should be string') }
those part of code run in sync, not async, but the rest part of code for 'fileSize' is aysnc function. Normally a function should be always sync or async.
Why? If we call the fileSize with wrong params:
fileSize(1, (err, size) => { if (err) throw err; console.log(`Size in KB: ${size/1024}`); });
It ouput:
/* throw new TypeError('filename should be string') ^ TypeError: filename should be string */
Our console.log() is not running...
To fix it we can use 'process.nextTick', it run before 'event loop' and right after 'call stack is empty':
const fs = require('fs'); function fileSize (fileName, cb) { if (typeof fileName !== 'string') { return process.nextTick( cb, new TypeError('filename should be string') ) } fs.stat(fileName, (err, stats) => { if (err) { return cb(err) } cb(null, stats.size); }); } fileSize(1, (err, size) => { if (err) throw err; console.log(`Size in KB: ${size/1024}`); }); console.log('Hello!'); /* Hello! C:\Users\z000879\learn\maybe\src\process.js:21 if (err) throw err; ^ TypeError: filename should be string */
This time, our 'Hello' was printed out before error was throw.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2017-03-28 [Grid Layout] Use auto-fill and auto-fit if the number of repeated grid tracks is not to be def
2017-03-28 [Grid Layout] Use the repeat function to efficiently write grid-template values
2017-03-28 [Grid Layout] Use the minmax function to specify dynamically-sized tracks
2017-03-28 [Jest] Snapshot
2017-03-28 [Flow] More tips about Flow
2017-03-28 [Grid Layout] Describe a grid layout using grid-template-areas
2016-03-28 [Angular 2] @Input Custom public property naming