Open LinkXSystem opened 3 years ago
Node.js 如何处理 ES6 模块
用法上面,require()是同步加载,后面的代码必须等待这个命令执行完,才会执行。import命令则是异步加载,或者更准确地说,ES6 模块有一个独立的静态解析阶段,依赖关系的分析是在那个阶段完成的,最底层的模块第一个执行。
参考文章:Node.js 如何处理 ES6 模块
npx 的使用
npx --no-install http-server
npx --ignore-existing http-server
判断是否为 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;
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
}
CommonJS 模块的重要特性是加载时执行,即脚本代码在
require
的时候,就会全部执行。CommonJS 的做法是,一旦出现某个模块被"循环加载",就只输出已经执行的部分,还未执行的部分不会输出。ES6 模块的运行机制与 CommonJS 不一样,它遇到模块加载命令
import
时,不会去执行模块,而是只生成一个引用。等到真的需要用到时,再到模块里面去取值。因此,ES6 模块是动态引用,不存在缓存值的问题,而且模块里面的变量,绑定其所在的模块。参考文章:JavaScript 模块的循环加载