diff --git a/doc/api/cli.md b/doc/api/cli.md index 74863327c73746..10ed548f9501ab 100644 --- a/doc/api/cli.md +++ b/doc/api/cli.md @@ -540,14 +540,16 @@ $ ls *.cpuprofile CPU.20190409.202950.15293.0.0.cpuprofile ``` -If `--cpu-prof-name` is specified, the provided value will be used as-is; patterns such as -`${hhmmss}` or `${pid}` are not supported. +If `--cpu-prof-name` is specified, the provided value is used as a template +for the file name. Some placeholders are supported and will be substituted +at runtime: + +* `${pid}` — the current process ID ```console $ node --cpu-prof --cpu-prof-name 'CPU.${pid}.cpuprofile' index.js $ ls *.cpuprofile -'CPU.${pid}.cpuprofile' -``` +CPU.15293.cpuprofile ### `--cpu-prof-dir` @@ -659,7 +661,7 @@ For example, the following script will not emit ```mjs import sys from 'node:sys'; -``` +```` ```cjs const sys = require('node:sys'); diff --git a/src/inspector_profiler.cc b/src/inspector_profiler.cc index f09dd04ccd7f6e..f73491342de0b5 100644 --- a/src/inspector_profiler.cc +++ b/src/inspector_profiler.cc @@ -8,6 +8,7 @@ #include "node_file.h" #include "node_internals.h" #include "util-inl.h" +#include "uv.h" #include "v8-inspector.h" #include @@ -465,6 +466,26 @@ static void EndStartedProfilers(Environment* env) { } } +static std::string ReplacePlaceholders(const std::string& pattern) { + std::string result = pattern; + + static const std::unordered_map> + kPlaceholderMap = { + {"${pid}", []() { return std::to_string(uv_os_getpid()); }}, + // TODO(haramj): Add more placeholders as needed. + }; + + for (const auto& [placeholder, getter] : kPlaceholderMap) { + size_t pos = 0; + while ((pos = result.find(placeholder, pos)) != std::string::npos) { + result.replace(pos, placeholder.length(), getter()); + pos += getter().length(); + } + } + + return result; +} + void StartProfilers(Environment* env) { AtExit(env, [](void* env) { EndStartedProfilers(static_cast(env)); @@ -486,7 +507,9 @@ void StartProfilers(Environment* env) { DiagnosticFilename filename(env, "CPU", "cpuprofile"); env->set_cpu_prof_name(*filename); } else { - env->set_cpu_prof_name(env->options()->cpu_prof_name); + std::string resolved_name = + ReplacePlaceholders(env->options()->cpu_prof_name); + env->set_cpu_prof_name(resolved_name); } CHECK_NULL(env->cpu_profiler_connection()); env->set_cpu_profiler_connection(