我用的是Pino美元.我正在try 加密日志(log)流并将其写入文件.我可以实现这一点的一种方法是创建一个pipeline,在其中我可以转换数据并加密其内容,如下所示(效果很好):
import build from "pino-abstract-transport";
import { pipeline, Transform } from "node:stream";
import crypto from "node:crypto";
const ALGORITHM = "aes-256-ctr";
export default async function (options: { password: string }) {
const password = Buffer.from(options.password, "hex");
const iv = crypto.randomBytes(16);
return build(function (source) {
const myTransportStream = new Transform({
autoDestroy: true,
objectMode: true,
transform(chunk, _enc, end) {
const encrypt = crypto.createCipheriv(ALGORITHM, password, iv);
const data = encrypt.update(JSON.stringify(chunk));
const encrypted = Buffer.concat([data, encrypt.final()]);
this.push(encrypted.toString("hex") + '\n');
end();
},
});
pipeline(source, myTransportStream, () => {});
return myTransportStream;
}, {
enablePipelining: true,
});
}
我如何才能重用相同的const encrypt = crypto.createCipheriv(ALGORITHM, password, iv);
个实例,而不是每次都创建一个新的实例?我是否通过进行这种重构获得了一些性能?
我试过这个:
import build from "pino-abstract-transport";
import { pipeline, Transform } from "node:stream";
import crypto from "node:crypto";
const ALGORITHM = "aes-256-ctr";
export default async function (options: { password: string }) {
let initiated = false;
const password = Buffer.from(options.password, "hex");
const iv = crypto.randomBytes(16);
const encrypt = crypto.createCipheriv(ALGORITHM, password, iv);
return build(function (source) {
const myTransportStream = new Transform({
autoDestroy: true,
objectMode: true,
transform(chunk, _enc, end) {
if (!initiated) {
initiated = true;
this.push(Buffer.concat([iv, chunk]));
} else {
this.push(chunk);
}
end();
},
});
pipeline(source, encrypt, myTransportStream, () => {});
return myTransportStream;
}, {
enablePipelining: true,
});
}
但我得到了:
TypeError [ERR_INVALID_ARG_TYPE]: The "chunk" argument must be of type string or an instance of Buffer or Uint8Array. Received an instance of Object
at new NodeError (node:internal/errors:372:5)
at _write (node:internal/streams/writable:312:13)
at Cipheriv.Writable.write (node:internal/streams/writable:334:10)
at Transform.ondata (node:internal/streams/readable:754:22)
at Transform.emit (node:events:527:28)
at addChunk (node:internal/streams/readable:315:12)
at readableAddChunk (node:internal/streams/readable:289:9)
at Transform.Readable.push (node:internal/streams/readable:228:10)
at push (/mnt/spare/ent/back/Plugin-Stix-Core-API/node_modules/split2/index.js:76:10)
at Transform.transform [as _transform] (/mnt/spare/ent/back/Plugin-Stix-Core-API/node_modules/split2/index.js:44:7)
Emitted 'error' event on ThreadStream instance at:
不必担心微观优化,但如果您能够并且想要指出/提出论点,请随意这样做.
我使用的是Fastify的Pino配置,它基本上与Vanilla Pino包的配置相同:
transport: {
pipeline: [
{
target: "./transform-log.js",
options: {
password:
"f8647d5417039b42c88a75897109049378cdfce528a7e015656bd23cd18fb78a",
},
},
{
target: "pino/file",
options: {
destination: file,
},
},
],
},