LinkXSystem / learn-guide

有趣的学习笔记 (*^_^*)
https://linkxsystem.github.io/
3 stars 1 forks source link

Node 小技巧 (。・∀・)ノ゙ #42

Open LinkXSystem opened 3 years ago

LinkXSystem commented 3 years ago

循环加载

参考文章:JavaScript 模块的循环加载

LinkXSystem commented 3 years ago

Node.js 如何处理 ES6 模块

用法上面,require()是同步加载,后面的代码必须等待这个命令执行完,才会执行。import命令则是异步加载,或者更准确地说,ES6 模块有一个独立的静态解析阶段,依赖关系的分析是在那个阶段完成的,最底层的模块第一个执行。

参考文章:Node.js 如何处理 ES6 模块

LinkXSystem commented 3 years ago

npx 的使用

npx --no-install http-server
npx --ignore-existing http-server
LinkXSystem commented 3 years ago

判断是否为 stream

'use strict';

const isStream = stream =>
    stream !== null &&
    typeof stream === 'object' &&
    typeof stream.pipe === 'function';

isStream.writable = stream =>
    isStream(stream) &&
    stream.writable !== false &&
    typeof stream._write === 'function' &&
    typeof stream._writableState === 'object';

isStream.readable = stream =>
    isStream(stream) &&
    stream.readable !== false &&
    typeof stream._read === 'function' &&
    typeof stream._readableState === 'object';

isStream.duplex = stream =>
    isStream.writable(stream) &&
    isStream.readable(stream);

isStream.transform = stream =>
    isStream.duplex(stream) &&
    typeof stream._transform === 'function' &&
    typeof stream._transformState === 'object';

module.exports = isStream;

来源项目:https://github.com/sindresorhus/is-stream

LinkXSystem commented 3 years ago

JSON.stringify 的高效版本

function createStringify(schema) {
    // 创建字符串模版
    function createTemplate(s, prefix = '') {
        let template = '{';

        const inner = [];
        for (const key in s) {
            const type = s[key].type || s[key];

            switch (type) {
                case Number:
                    inner.push(`\\"${key}\\": \$\{json${prefix}[${'"' + key + '"'}]\}`);
                    break;
                case String:
                    inner.push(`\\"${key}\\": \\"\$\{json${prefix}[${'"' + key + '"'}]\}\\"`);
                    break;
                case Object:
                    inner.push(`\\"${key}\\": ${createTemplate(s[key].schema, `${prefix}[${'"' + key + '"'}]`)}`);
                    break;
                default:
                    break;
            }
        }

        template += inner.join(', ');
        template += '}';

        return template
    }

    const template = createTemplate(schema);
    // MDN文档:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function
    return new Function('json', `return \`${template}\``);
}

const constants = {
    Number,
    String,
    Object
}

module.exports = {
    createStringifyTemplateBySchema,
    constants
}