[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.

 

posted @   Zhentiw  阅读(272)  评论(0编辑  收藏  举报
编辑推荐:
· 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
点击右上角即可分享
微信分享提示