# Why 24/7 Node.js scripts on Windows freeze or stop

> A Node script left running on a Windows PC can hang after one mouse click, die with its window or refuse to start. Five causes, their fixes and a test.

Published 2026-11-22 · https://aiskills402.com/blog/nodejs-script-24-7-windows-freezes-or-stops

A Node.js script that runs 24/7 on Windows usually fails because of Windows rather than its own logic, and it leaves almost nothing to read afterwards. Three shapes cover most cases. The process is still listed but does nothing: someone clicked inside its console window, and a text selection made through [QuickEdit](https://learn.microsoft.com/windows/console/setconsolemode) is holding the output. Or the process has vanished and its log stops mid-way: the window was closed, or a stream error reached no listener. Or a new start refuses with "already running" while no copy runs: the lock file holds a process number that Windows has since handed to some other program. A fourth problem shows up later, as an empty or half-written state file after the power went out. Each has a fix of a few lines, and each fix can be tested by causing the failure on purpose.

## Tell the symptoms apart first

Before changing code, match what you see to one of these:

- **Still running at 0 % CPU, nothing new in the log, and the title bar of its window now starts with the word Select.** A selection in the console is holding the output (section 1).
- **Gone overnight, with the last log line cut off or missing.** A closed window (section 2) or a stream error nobody listened for (section 5).
- **"Already running" right after a reboot, yet nothing runs.** A stale lock (section 3).
- **A state file that is empty or broken after a power cut.** An unsafe save, or a loader that treats a broken file as a blank one (section 4).

Everything we measured below comes from our own unattended scripts on one PC with Windows 11 and Node 24, between September and November 2026. A frozen script raises no error at all, so from the outside only something that [measures silence instead of counting errors](https://aiskills402.com/blog/watchdog-alerts-silent-and-noisy) will ever notice it.

## 1. A click in the console window pauses the script

A Windows console lets a person mark text with the mouse. Microsoft calls this the QuickEdit input mode, and its documentation lists it among the modes that a newly created console has switched on ([SetConsoleMode](https://learn.microsoft.com/windows/console/setconsolemode)). What that page leaves out is the fate of a program that keeps printing while a selection is open.

On our PC the word Select appeared at the front of the window's title, and the following `console.log` call did not return until the selection was cleared. Task Manager still listed the process, using no CPU, while the log file stayed the same size. In one case it stood like that for about four hours before anyone looked. Nothing crashed, so nothing was written anywhere.

Asking people not to click is no fix: the window looks like any other, and sooner or later somebody clicks. Switching QuickEdit off is possible (the same page shows how a program does it), but that is a setting someone can turn back on, and it does nothing about the failure in section 2. The lasting fix is that the unattended mode never writes to a console. Each message is appended to a log file; printing to the screen is kept for a person who starts the script by hand to watch it.

```js
import { appendFileSync } from 'node:fs';

const LOG_PATH = new URL('./worker.log', import.meta.url);
const watchedByHand = process.argv.includes('--watch') && process.stdout.isTTY;

export function log(message) {
  const entry = new Date().toISOString() + ' ' + message + '\n';
  appendFileSync(LOG_PATH, entry);              // the file is the record
  if (watchedByHand) process.stdout.write(entry); // only when someone asked to watch
}
```

## 2. Closing the window ends the script

This is a separate failure from the click. When a person closes a console, Windows sends a close signal to every process attached to it. The default response ends the process. A program may register its own handler to tidy up, but every outcome the documentation lists ends with the process terminated, and the time allowed for the cleanup is five seconds by default ([HandlerRoutine](https://learn.microsoft.com/windows/console/handlerroutine)). There is no answer that means "keep me running".

Our case: the script had been started with `start /min node ...`, so it sat on the taskbar as a minimised window that looked idle and empty. It was closed to tidy up. The script went with it, with no error and no final line in the log.

So start the script with no window at all, and follow its log in a separate window whose only job is reading it. PowerShell's `Start-Process` accepts a hidden window style, and the process it launches carries on independently of whoever launched it ([Start-Process](https://learn.microsoft.com/powershell/module/microsoft.powershell.management/start-process?view=powershell-5.1)).

```bat
@echo off
rem start-worker.cmd: no window; the worker writes only to worker.log
powershell -NoProfile -Command "Start-Process node -ArgumentList 'worker.mjs' -WindowStyle Hidden -WorkingDirectory '%~dp0.'"
```

```bat
@echo off
rem watch-worker.cmd: reads the log; closing or clicking here changes nothing
powershell -NoProfile -Command "Get-Content '%~dp0worker.log' -Tail 50 -Wait"
```

A scheduled task also starts a program without a window. `start /b` is not a substitute: the script stays tied to the console of whichever `cmd` started it, so closing that console still ends the script.

## 3. "Already running" after a reboot: the PID in the lock

A lock file stops a second copy from starting. The usual version writes `process.pid` into the file and, at the next start, asks whether that number is alive. On Windows that question is unsafe after a restart. Microsoft's page on the Win32_Process class says a process number is valid only while its process lives, that the same number may be given to a new process afterwards, and therefore that a number alone cannot tell you a particular program is still running ([Win32_Process](https://learn.microsoft.com/windows/win32/cimwin32prov/win32-process)).

We hit exactly that after a power cut. The number in our lock now belonged to an unrelated program, the check said "alive", and the script declined to start on every attempt. Matching the image name does not rescue it either, because any other Node program also runs as `node.exe`.

The fix: read the number, ask Windows which command started that process (the same class exposes it), and trust the lock only when this script's file name appears in that command. The query took about 0.5 s on our machine, so ask once at start, not on every tick. If the query itself fails, refuse to start: two copies writing the same files is worse than one missed start. The stop `.cmd` needs the same test before it kills anything, or it may end the wrong program.

```js
import { execFileSync } from 'node:child_process';

const PS_ARGS = ['-NoProfile', '-NonInteractive', '-Command'];

// true only when that PID was started for this script; throws when Windows cannot be asked
function lockBelongsToUs(pid, scriptFile) {
  const id = Number(pid);
  const ask = `(Get-CimInstance -ClassName Win32_Process -Filter "ProcessId = ${id}").CommandLine`;
  const started = execFileSync('powershell', [...PS_ARGS, ask], { windowsHide: true, encoding: 'utf8' });
  return started.toLowerCase().includes(scriptFile.toLowerCase());
}
```

## 4. Saving state: fsync, keep a backup, never read broken as empty

The usual careful save writes a temporary file and renames it over the real one. Node's rename does replace an existing target ([fs docs](https://nodejs.org/api/fs.html)), but nothing in that sequence asks the system to put the new bytes on the disk before the swap. That request is `fsync`, and the same docs warn that what it achieves depends on the operating system and the device. On our PC, a write followed by a rename with no fsync in between could leave a broken file once the power went off.

The second half of the bug sits in the loader. Code that treats every failure to read or parse the file as "no state yet" will save that emptiness on its next tick, and everything the script had collected is gone. Keep two cases apart. No file at all means this is the first run, so begin with nothing. A file that exists but will not parse is evidence: rename it to something else so it survives, fall back to the backup, and record what happened; the broken copy is never saved over.

```js
import {
  openSync, writeSync, fsyncSync, closeSync,
  copyFileSync, renameSync, existsSync, readFileSync,
} from 'node:fs';

export function saveState(target, data) {
  const pending = target + '.tmp';
  const handle = openSync(pending, 'w');
  try {
    writeSync(handle, JSON.stringify(data));
    fsyncSync(handle);                       // on the disk before the swap
  } finally {
    closeSync(handle);
  }
  if (existsSync(target)) copyFileSync(target, target + '.bak');
  renameSync(pending, target);
}

export function loadState(target) {
  if (!existsSync(target)) return {};        // first run
  try {
    return JSON.parse(readFileSync(target, 'utf8'));
  } catch (err) {
    const keptAs = target + '.broken-' + Date.now();
    renameSync(target, keptAs);              // keep the evidence
    log('state unreadable, kept as ' + keptAs + ': ' + err.message);
    return JSON.parse(readFileSync(target + '.bak', 'utf8')); // a bad backup stops the start loudly
  }
}
```

## 5. A dropped connection kills the whole process

A script that reads a compressed feed often does it as `Readable.fromWeb(res.body).pipe(gunzip)`. When the connection drops halfway, the failure arrives as an `'error'` event on one stream. `.pipe()` does not hand it to the next stream; the stream docs even warn that the destination is not closed for you ([stream docs](https://nodejs.org/api/stream.html)). An `'error'` event that has no listener is thrown, its stack is printed, and Node exits ([events docs](https://nodejs.org/api/events.html)).

A `try/catch` around the download loop does not help, because the error comes later, from an event, not from the line you awaited. We reproduced it: the process ended without a single line in the log and left its lock file behind for the next start to stumble over.

The fix is `pipeline` from `node:stream/promises`. It passes an error from any stage to the caller and closes every stream in the chain, so one `await` inside your normal try/catch sees the failure and the retry logic gets its turn.

```js
import { pipeline } from 'node:stream/promises';
import { Readable } from 'node:stream';
import { createGunzip } from 'node:zlib';
import { createInterface } from 'node:readline';

async function readFeed(url, onLine) {
  const response = await fetch(url);
  if (!response.ok) throw new Error('feed answered ' + response.status);
  const compressed = Readable.fromWeb(response.body);
  await pipeline(compressed, createGunzip(), async function (text) {
    for await (const row of createInterface({ input: text, crlfDelay: Infinity })) onLine(row);
  });
}
```

Add one safety net at process level: handlers for `uncaughtException` and `unhandledRejection` whose first job is to record the error in the log file synchronously, then release the lock, set `process.exitCode = 1` and let the normal shutdown code stop the timers. Do not finish them with `process.exit()`: on Node 24 we saw it end with code 127 once a second `fetch` to the same host had run, so anything that reads the code mistakes the outcome. A script that dies with a line in its log can be fixed the next morning; one that dies silently cannot.

## Two traps in the .cmd files that launch it

In a `.cmd`, when an `echo` sits inside an `if (...) ( ... )` block, a closing bracket in its text ends the block early: `cmd` prints `. was unexpected at this time.` and skips everything after it. Drop the brackets from that text, write each as `^)`, or jump to a label with `goto`. Separately, `timeout` refuses to wait when it has no console to read keys from, which is the case when another program or a hidden start runs the file: it prints `Input redirection is not supported` and returns at once. `ping -n 4 127.0.0.1 >nul` waits about three seconds in any setting. Try every new `.cmd` twice before trusting it: once with the worker running and once with it stopped.

## A check that can fail

A fix is proved only by causing the failure again on purpose and watching the result change:

1. Start the script hidden, open the watcher, and drag a selection inside the watcher window for a minute. The log must keep growing. Close the watcher; `Get-Process node` must still list the worker.
2. Write the PID of a program that is certainly running, such as `explorer.exe`, into the lock file and start the script. With the fix it starts and logs a stale lock; without it, it says "already running".
3. Cut the state file in half with an editor and start the script. It must keep the broken copy under another name, load the backup and report it in the log. An empty state means the loader still treats broken as blank.
4. Point the feed reader at a large download and switch the network off halfway. The log must show the error and a retry. A process that vanished means a `.pipe()` is still somewhere in the chain.

Run each test once against the old code as well. A test that also passes before the fix is not measuring this failure.

If the same script also posts text to an API from Windows, the request body has a trap of its own: [Git's curl and Windows PowerShell can mangle Cyrillic and typographic quotes](https://aiskills402.com/blog/windows-curl-powershell-utf8-what-models-miss) while the server still reports success.

## When this does not apply

- **One machine.** Every measured fact here comes from one PC with Windows 11 and Node 24. Other Windows builds, other Node versions and other terminal programs were not tried, and the console behaviour in sections 1 and 2 is the part most likely to differ elsewhere.
- **Few cases.** Each fact rests on the incident we recorded for it, usually a single one, not on a survey of many machines. The four hours is one case, and the half-second query time was measured on that one PC.
- **No console, no window traps.** A Windows service or a service wrapper has no console window, so neither of the first two sections applies to it. Such tools bring their own restart and logging behaviour, which we did not test.
- **Other systems.** On Linux and macOS the window traps do not exist in this form. The stream section is about Node itself and holds everywhere; we did not test the lock and save sections there.
- **fsync narrows the risk, it does not remove it.** What a flush guarantees depends on the disk and the system, and anything collected since the final successful save is lost whatever the code does.

## Our skills for this topic

- The [review skill for Windows background scripts](https://aiskills402.com/skills/windows-background-script-review) reads a long-running Node script together with the `.cmd` files that start and stop it, and points out each of the failures above that the pasted code contains, with a fix in code for each and a verdict at the end. Asked about a symptom instead, it names the likely cause first.
- The [skill for UTF-8 request bodies sent from Windows](https://aiskills402.com/skills/windows-utf8-request-body) covers the moment such a script sends text with curl or PowerShell: it keeps Cyrillic, dashes and typographic quotes byte for byte on the way to the server and reads the record back to compare.
- The [watchdog and staleness alarm review](https://aiskills402.com/skills/watchdog-alert-review) checks the watchdog that is meant to notice a frozen or dead script: whether it measures silence the right way, stays quiet about a dead source, or floods the inbox about healthy ones.
