Skip to content
12 changes: 7 additions & 5 deletions doc/api/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`

Expand Down Expand Up @@ -659,7 +661,7 @@ For example, the following script will not emit

```mjs
import sys from 'node:sys';
```
````

```cjs
const sys = require('node:sys');
Expand Down
25 changes: 24 additions & 1 deletion src/inspector_profiler.cc
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include "node_file.h"
#include "node_internals.h"
#include "util-inl.h"
#include "uv.h"
#include "v8-inspector.h"

#include <cinttypes>
Expand Down Expand Up @@ -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<std::string, std::function<std::string()>>
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<Environment*>(env));
Expand All @@ -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(
Expand Down