意味着通过 console.log 可以间接的输出彩色文本了,不用再引入三方库了。
- const { styleText } = require('node:util');
- const errorMessage = styleText('red', 'Error! Error!');
- console.log(errorMessage);
通过两个 API 支持加载和解析环境变量:process.loadEnvFile(path)、util.parseEnv(content)
- MULTI_LINE="HELLO
- WORLD"
这个 sea 以前没注意过,原来是 Node.js 又增加了一个新模块,sea 的全称为 Single executable applications,即单一执行模块。后面单独写个文章来介绍下~
以下是本次 Node.js 的更新:
“用户现在可以通过将键路径字典添加到配置作为资产字段来包含资产。在构建时,Node.js 将从指定路径读取资源并将它们捆绑到准备的 blob 中。在生成的可执行文件中,用户可以使用
sea.getAsset()和sea.getAssetAsBlob()API 检索资产。”
- {
- "main": "/path/to/bundled/script.js",
- "output": "/path/to/write/the/generated/blob.blob",
- "assets": {
- "a.jpg": "/path/to/a.jpg",
- "b.txt": "/path/to/b.txt"
- }
- }
- const { getAsset } = require('node:sea');
- // Returns a copy of the data in an ArrayBuffer
- const image = getAsset('a.jpg');
- // Returns a string decoded from the asset as UTF8.
- const text = getAsset('b.txt', 'utf8');
- // Returns a Blob containing the asset without copying.
- const blob = getAssetAsBlob('a.jpg');
第一步,将 test.js 和 test.txt 写入当前运行脚本所在目录。
第二步,编译一个加载 test.mjs 和 test.json 的脚本,就好像该脚本放置在同一目录中一样。
- const { Script, constants } = require('node:vm');
- const { resolve } = require('node:path');
- const { writeFileSync } = require('node:fs');
- // Write test.js and test.txt to the directory where the current script
- // being run is located.
- writeFileSync(
- resolve(__dirname, 'test.mjs'),
- 'export const filename = "./test.json";'
- );
- writeFileSync(resolve(__dirname, 'test.json'), '{"hello": "world"}');
- // Compile a script that loads test.mjs and then test.json
- // as if the script is placed in the same directory.
- const script = new Script(
- `(async function() {
- const { filename } = await import('./test.mjs');
- return import(filename, { with: { type: 'json' } })
- })();`,
- {
- filename: resolve(__dirname, 'test-with-default.js'),
- importModuleDynamically: constants.USE_MAIN_CONTEXT_DEFAULT_LOADER,
- }
- );
- // { default: { hello: 'world' } }
- script.runInThisContext().then(console.log);
crypto.hash() 方法crypto.hash() 比 crypto.createHash() 快 1.2 - 2 倍,并且由于不会创建中间对象,因此会产生更少的内存开销
- const crypto = require('node:crypto');
- // Hashing a string and return the result as a hex-encoded string.
- const string = 'Node.js';
- // 10b3493287f831e81a438811a1ffba01f8cec4b7
- console.log(crypto.hash('sha1', string));
参考 https://nodejs.org/en/blog/release/v21.7.0