{"id":13495545,"url":"https://github.com/gajus/turbowatch","last_synced_at":"2025-05-15T09:08:14.073Z","repository":{"id":82386706,"uuid":"606292687","full_name":"gajus/turbowatch","owner":"gajus","description":"Extremely fast file change detector and task orchestrator for Node.js.","archived":false,"fork":false,"pushed_at":"2025-05-14T16:20:02.000Z","size":912,"stargazers_count":951,"open_issues_count":25,"forks_count":24,"subscribers_count":4,"default_branch":"main","last_synced_at":"2025-05-14T17:28:25.990Z","etag":null,"topics":["file","watch"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/gajus.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null},"funding":{"github":"gajus","patreon":"gajus"}},"created_at":"2023-02-25T03:50:47.000Z","updated_at":"2025-05-14T16:20:07.000Z","dependencies_parsed_at":null,"dependency_job_id":"78c0f79e-a43f-441b-b21b-cca9ae91a318","html_url":"https://github.com/gajus/turbowatch","commit_stats":{"total_commits":107,"total_committers":2,"mean_commits":53.5,"dds":0.009345794392523366,"last_synced_commit":"b8a1e2c4fce3fb1c49de31b045f2143bbafd398f"},"previous_names":["gajus/watchrow"],"tags_count":110,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gajus%2Fturbowatch","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gajus%2Fturbowatch/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gajus%2Fturbowatch/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/gajus%2Fturbowatch/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/gajus","download_url":"https://codeload.github.com/gajus/turbowatch/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254198381,"owners_count":22030956,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["file","watch"],"created_at":"2024-07-31T19:01:35.761Z","updated_at":"2025-05-15T09:08:09.062Z","avatar_url":"https://github.com/gajus.png","language":"TypeScript","funding_links":["https://github.com/sponsors/gajus","https://patreon.com/gajus"],"categories":["TypeScript"],"sub_categories":[],"readme":"# Turbowatch 🏎\n\nExtremely fast file change detector and task orchestrator for Node.js.\n\nIf you ever wanted something like [Nodemon](https://nodemon.io/) but more capable, then you are at the right place.\n\nBasic usage:\n\n```bash\nnpm install turbowatch\ncat \u003e turbowatch.ts \u003c\u003c'EOD'\nimport { defineConfig } from 'turbowatch';\n\nexport default defineConfig({\n  project: __dirname,\n  triggers: [\n    {\n      expression: ['match', '*.ts', 'basename'],\n      name: 'build',\n      onChange: async ({ spawn }) =\u003e {\n        await spawn`tsc`;\n      },\n    },\n  ],\n});\nEOD\nnpm exec turbowatch ./turbowatch.ts\n```\n\n\u003e **Note** See [logging](#logging) instructions to print logs that explain what Turbowatch is doing.\n\nRefer to recipes:\n\n* [Rebuilding assets when file changes are detected](#rebuilding-assets-when-file-changes-are-detected)\n* [Restarting server when file changes are detected](#restarting-server-when-file-changes-are-detected)\n* [Retrying failing triggers](#retrying-failing-triggers)\n* [Gracefully terminating Turbowatch](#gracefully-terminating-turbowatch)\n* [Handling the `AbortSignal`](#handling-the-abortsignal)\n* [Tearing down project](#tearing-down-project)\n* [Throttling `spawn` output](#throttling-spawn-output)\n* [Watching multiple scripts](#watching-multiple-scripts)\n* [Using custom file watching backend](#using-custom-file-watching-backend)\n\n||Turbowatch|Nodemon|\n|---|---|---|\n|[Node.js interface (scriptable)](#api)|✅|❌\u003csup\u003e1\u003c/sup\u003e|\n|[Graceful termination (teardown)](#gracefully-terminating-turbowatch)|✅|❌\u003csup\u003e2\u003c/sup\u003e|\n|[Scriptable child processes (zx)](#spawn)|✅|❌|\n|Retries|✅|❌|\n|Debounce|✅|❌|\n|Interruptible workflows|✅|❌|\n|Concurrent workflows|✅|❌|\n|[Log grouping](#throttling-spawn-output)|✅|❌|\n|[Bring-your-own backend](#using-custom-file-watching-backend)|✅|❌|\n|Works with long-running processes|✅|✅|\n|Works with build utilities and REPLs|✅|✅|\n|Watch specific files or directories|✅|✅|\n|Ignoring specific files or directories|✅|✅|\n|Open source and available|✅|✅|\n\n\u003csup\u003e\u003csup\u003e1\u003c/sup\u003e Undocumented\u003c/sup\u003e\u003cbr\u003e\n\u003csup\u003e\u003csup\u003e2\u003c/sup\u003e Nodemon only provides the ability to [send a custom signal](https://github.com/remy/nodemon#gracefully-reloading-down-your-script) to the worker.\u003c/sup\u003e\u003cbr\u003e\n\n## API\n\n\u003e **Note** `defineConfig` is used to export configuration for the consumption by `turbowatch` program. If you want to run Turbowatch programmatically, then use `watch`. The API of both methods is equivalent.\n\nTurbowatch [defaults](#recipes) are a good choice for most projects. However, Turbowatch has _many_ options that you should be familiar with for advance use cases.\n\n```ts\nimport {\n  watch,\n  type ChangeEvent,\n} from 'turbowatch';\n\nvoid watch({\n  // Debounces triggers by 1 second.\n  // Most multi-file spanning changes are non-atomic. Therefore, it is typically desirable to\n  // batch together information about multiple file changes that happened in short succession.\n  // Provide { debounce: { wait: 0 } } to disable debounce.\n  debounce: {\n    wait: 1000,\n  },\n  // The base directory under which all files are matched.\n  // Note: This is different from the \"root project\" (https://github.com/gajus/turbowatch#project-root).\n  project: __dirname,\n  triggers: [\n    {\n      // Expression match files based on name.\n      // https://github.com/gajus/turbowatch#expressions\n      expression: [\n        'allof',\n        ['not', ['dirname', 'node_modules']],\n        [\n          'anyof',\n          ['match', '*.ts', 'basename'],\n          ['match', '*.tsx', 'basename'],\n        ]\n      ],\n      // Indicates whether the onChange routine should be triggered on script startup.\n      // Defaults to false. Set it to false if you would like onChange routine to not run until the first changes are detected.\n      initialRun: true,\n      // Determines what to do if a new file change is detected while the trigger is executing.\n      // If {interruptible: true}, then AbortSignal will abort the current onChange routine.\n      // If {interruptible: false}, then Turbowatch will wait until the onChange routine completes.\n      // Defaults to true.\n      interruptible: false,\n      // Name of the trigger. Used for debugging\n      // Must match /^[a-z0-9-_]+$/ pattern and must be unique.\n      name: 'build',\n      // Routine that is executed when file changes are detected.\n      onChange: async ({ spawn }: ChangeEvent) =\u003e {\n        await spawn`tsc`;\n        await spawn`tsc-alias`;\n      },\n      // Routine that is executed when shutdown signal is received.\n      onTeardown: async ({ spawn }) =\u003e {\n        await spawn`rm -fr ./dist`;\n      },\n      // Label a task as persistent if it is a long-running process, such as a dev server or --watch mode.\n      persistent: false,\n      // Retry a task if it fails. Otherwise, watch program will throw an error if trigger fails.\n      // Defaults to { retries: 3 }\n      retry: {\n        retries: 3,\n      },\n    },\n  ],\n});\n```\n\n## Motivation\n\nTo abstract the complexity of orchestrating file watching operations.\n\nFor context, we are using [Turborepo](https://turbo.build/). The reason this project came to be is because Turborepo does not have \"watch\" mode (issue [#986](https://github.com/vercel/turbo/issues/986)).\n\nAt first, we attempted to use a combination of `tsc --watch`, `concurrently` and Nodemon, but started to run into things breaking left and right, e.g.\n\n* services restarting prematurely (before all the assets are built)\n* services failing to gracefully shutdown and then failing to start, e.g. because ports are in use\n\nFurthermore, the setup for each workspace was repetitive and not straightforward, and debugging issues was not a great experience because you have many workspaces running in watch mode producing tons of logs. Many of the workspaces being dependencies of each other, this kept re-triggering watch operations causing the mentioned issues.\n\nIn short, it quickly became clear that we need the ability to have more control over the orchestration of what/when needs to happen when files change.\n\nWe started with a script. At first I added _debounce_. That improved things. Then I added _graceful termination_ logic, which mostly made everything work. We still had occasional failures due to out-of-order events, but adding _retry_ logic fixed that too... At the end, while we got everything to work, it took a lot of effort and it still was a collection of hacky scripts that are hard to maintain and debug, and that's how Turbowatch came to be –\n\nTurbowatch is a toolbox for orchestrating and debugging file watching operations based on everything we learned along the way.\n\n\u003e **Note** If you are working on a very simple project, i.e. just one build step or just one watch operation, then **you don't need Turbowatch**. Turbowatch is designed for monorepos or otherwise complex workspaces where you have dozens or hundreds of build steps that depend on each other (e.g. building and re-building dependencies, building/starting/stopping Docker containers, populating data, sending notifications, etc).\n\nWe also [shared these learnings](https://github.com/vercel/turbo/issues/986#issuecomment-1477360394) with Turborepo team in hopes that it will help to design an embedded file watching experience.\n\n## Use Cases\n\nTurbowatch can be used to automate any sort of operations that need to happen in response to files changing, e.g.,\n\n* You can run (and conditionally restart) long-running processes (like your Node.js application)\n* You can build assets (like TypeScript and Docker images)\n\n## `spawn`\n\nTurbowatch exposes `spawn` function that is an instance of [zx](https://github.com/google/zx). Use it to evaluate shell commands:\n\n```ts\nasync ({ spawn }: ChangeEvent) =\u003e {\n  await spawn`tsc`;\n  await spawn`tsc-alias`;\n},\n```\n\nThe reason Turbowatch abstracts `zx` is to enable graceful termination of child-processes when triggers are configured to be `interruptible`.\n\n## Persistent tasks\n\nYour setup may include tasks that are not designed to exit, e.g. `next dev` (starts Next.js in development mode).\n\nIt is important that these tasks are marked as `persistent` to distinguish them from tasks that run to completion as that changes how Turbowatch treats them.\n\n||Persistent|Non-Persistent|\n|---|---|---|\n|Ignore `FileChangeEvent` if `{ interruptible: false }`|✅|❌|\n\n## Expressions\n\nExpressions are used to match files. The most basic expression is `match` – it evaluates as true if a glob pattern matches the file, e.g.\n\nMatch all files with `*.ts` extension:\n\n```ts\n['match', '*.ts', 'basename']\n```\n\nExpressions can be combined using `allof` and `anyof`, e.g.,\n\nMatch all files with `*.ts` or `*.tsx` extensions:\n\n```ts\n[\n  'anyof', \n  ['match', '*.ts', 'basename'],\n  ['match', '*.tsx', 'basename']\n]\n```\n\nFinally, `not` evaluates as true if the sub-expression evaluated as false, i.e. inverts the sub-expression.\n\nMatch all files with `*.ts` extension, but exclude `index.ts`:\n\n```ts\n[\n  'allof', \n  ['match', '*.ts', 'basename'],\n  [\n    'not',\n    ['match', 'index.ts', 'basename']\n  ]\n]\n```\n\nThis is the gist behind Turbowatch expressions. However, there are many more expressions. Inspect `Expression` type for further guidance.\n\n```ts\ntype Expression =\n  // Evaluates as true if all of the grouped expressions also evaluated as true.\n  | ['allof', ...Expression[]]\n  // Evaluates as true if any of the grouped expressions also evaluated as true.\n  | ['anyof', ...Expression[]]\n  // Evaluates as true if a given file has a matching parent directory.\n  | ['dirname' | 'idirname', string]\n  // Evaluates as true if a glob matches against the basename of the file.\n  | ['match' | 'imatch', string, 'basename' | 'wholename']\n  // Evaluates as true if the sub-expression evaluated as false, i.e. inverts the sub-expression.\n  | ['not', Expression];\n```\n\n\u003e **Note** Turbowatch expressions are a subset of [Watchman expressions](https://facebook.github.io/watchman/docs/expr/allof.html). Originally, Turbowatch was developed to leverage Watchman as a superior backend for watching a large number of files. However, along the way, we discovered that Watchman does not support symbolic links (issue [#105](https://github.com/facebook/watchman/issues/105#issuecomment-1469496330)). Unfortunately, that makes Watchman unsuitable for projects that utilize linked dependencies (which is the direction in which the ecosystem is moving for dependency management in monorepos). As such, Watchman was replaced with chokidar. We are hoping to provide Watchman as a backend in the future. Therefore, we made Turbowatch expressions syntax compatible with a subset of Watchman expressions.\n\n\u003e **Note** Turbowatch uses [micromatch](https://github.com/micromatch/micromatch) for glob matching. Please note that you should be using forward slash (`/`) to separate paths, even on Windows.\n\n## Recipes\n\n### Rebuilding assets when file changes are detected\n\n```ts\nimport { watch } from 'turbowatch';\n\nvoid watch({\n  project: __dirname,\n  triggers: [\n    {\n      expression: [\n        'allof',\n        ['not', ['dirname', 'node_modules']],\n        ['match', '*.ts', 'basename'],\n      ],\n      name: 'build',\n      onChange: async ({ spawn }) =\u003e {\n        await spawn`tsc`;\n        await spawn`tsc-alias`;\n      },\n    },\n  ],\n});\n```\n\n### Restarting server when file changes are detected\n\n```ts\nimport { watch } from 'turbowatch';\n\nvoid watch({\n  project: __dirname,\n  triggers: [\n    {\n      expression: [\n        'allof',\n        ['not', ['dirname', 'node_modules']],\n        [\n          'anyof',\n          ['match', '*.ts', 'basename'],\n          ['match', '*.graphql', 'basename'],\n        ]\n      ],\n      // Because of this setting, Turbowatch will kill the processes that spawn starts\n      // when it detects changes when it detects a change.\n      interruptible: true,\n      name: 'start-server',\n      onChange: async ({ spawn }) =\u003e {\n        await spawn`tsx ./src/bin/wait.ts`;\n        await spawn`tsx ./src/bin/server.ts`;\n      },\n    },\n  ],\n});\n```\n\n### Watching `node_modules`\n\nThere is more than one way to watch `node_modules`. However, through trial and error we found that the following set of rules work the best for a generalized solution.\n\n```ts\nimport { watch } from 'turbowatch';\n\nvoid watch({\n  project: path.resolve(__dirname, '../..'),\n  triggers: [\n    {\n      expression: [\n        'anyof',\n        [\n          'allof',\n          ['dirname', 'node_modules'],\n          ['dirname', 'dist'],\n          ['match', '*', 'basename'],\n        ],\n        [\n          'allof',\n          ['not', ['dirname', 'node_modules']],\n          ['dirname', 'src'],\n          ['match', '*', 'basename'],\n        ],\n      ],\n      name: 'build',\n      onChange: async ({ spawn }) =\u003e {\n        return spawn`pnpm run build`;\n      },\n    },\n  ],\n});\n```\n\nThis setup makes an assumption that your workspaces sources are in `src` directory and `build` task outputs to `dist` directory.\n\n### Reusing expressions\n\nThis might be common sense, but since Turbowatch scripts are regular JavaScript scripts, you can (and should) abstract your expressions and routines.\n\nHow you do it is entirely up to you, e.g. You could abstract just expressions or you could go as far as abstracting the entire `trigger`:\n\n```ts\nimport { watch } from 'turbowatch';\nimport {\n  buildTrigger,\n} from '@/turbowatch';\n\nvoid watch({\n  project: __dirname,\n  triggers: [\n    buildTrigger(),\n  ],\n});\n```\n\nSuch abstraction helps to avoid errors that otherwise may occur due to duplicative code across workspaces.\n\n### Reducing unnecessary reloads\n\nSomething that is important to consider when orchestrating file watching triggers is how to avoid unnecessary reloads. Consider if this was your \"build\" script:\n\n```bash\nrm -fr dist \u0026\u0026 tsc \u0026\u0026 tsc-alias\n```\n\nand let's assume that you are using an expression such as this one to detect when dependencies are updated:\n\n```ts\n[\n  'allof',\n  ['dirname', 'node_modules'],\n  ['dirname', 'dist'],\n  ['match', '*'],\n],\n```\n\nRunning this script will produce at least 3 file change events:\n\n1. when `rm -fr dist` completes\n1. when `tsc` completes\n1. when `tsc-alias` completes\n\nWhat's even worse is that even if the output has not changed, you are still going to trigger file change events (because `dist` get replaced).\n\nTo some degree, `debounce` setting helps with this. However, it will only help if there is no more than 1 second (by default) inbetween every command.\n\nOne way to avoid this entirely is by using an intermediate directory to output files and swapping only the files that changed. Here is how we do it:\n\n```bash\nrm -fr .dist \u0026\u0026 tsc --project tsconfig.build.json \u0026\u0026 rsync -cr --delete .dist/ ./dist/ \u0026\u0026 rm -fr .dist\n```\n\nThis \"build\" script will always produce at most 1 event, and won't produce any events if the outputs have not changed.\n\nThis is not specific to Turbowatch, but something worth considering as you are designing your build pipeline.\n\n### Retrying failing triggers\n\nRetries are configured by passing a `retry` property to the trigger configuration.\n\n```ts\n/**\n * @property factor The exponential factor to use. Default is 2.\n * @property maxTimeout The maximum number of milliseconds between two retries. Default is 30,000.\n * @property minTimeout The number of milliseconds before starting the first retry. Default is 1000.\n * @property retries The maximum amount of times to retry the operation. Default is 3. Seting this to 1 means do it once, then retry it once.\n */\ntype Retry = {\n  factor?: number,\n  maxTimeout?: number,\n  minTimeout?: number,\n  retries?: number,\n}\n```\n\n### Gracefully terminating Turbowatch\n\n\u003e **Note** `SIGINT` is automatically handled if you are using `turbowatch` executable to evaluate your Turbowatch script. This examples shows how to programmatically gracefully shutdown Turbowatch if you choose not to use `turbowatch` program to evaluate your watch scripts.\n\n\u003e **Warning** Unfortunately, many tools do not allow processes to gracefully terminate. There are open support issues for this in npm ([#4603](https://github.com/npm/npm/issues/4603)), pnpm ([#2653](https://github.com/pnpm/pnpm/issues/2653#issuecomment-1476686711)) and yarn ([#4667](https://github.com/yarnpkg/yarn/issues/4667)), but they haven't been addressed. Therefore, do not wrap your `turbowatch` script execution using these tools if you require processes to gracefully terminate.\n\n`watch` returns an instance of `TurbowatchController`, which can be used to gracefully terminate the script:\n\n```ts\nconst { shutdown } = await watch({\n  project: __dirname,\n  triggers: [\n    {\n      name: 'test',\n      expression: ['match', '*', 'basename'],\n      onChange: async ({ spawn }) =\u003e {\n        // `sleep 60` will receive `SIGTERM` as soon as `shutdown()` is called.\n        await spawn`sleep 60`;\n      },\n    }\n  ],\n});\n\n// SIGINT is the signal sent when we press Ctrl+C\nprocess.once('SIGINT', () =\u003e {\n  void shutdown();\n});\n```\n\nInvoking `shutdown` will propagate an abort signal to all `onChange` handlers. The processes that were initiated using [`spawn`](#spawn) will receive `SIGTERM` signal.\n\n### Gracefully terminating Turbowatch using an `AbortController`\n\nIn addition to being to Turbowatch using the `shutdown` routine, Turbowatch instance can be shutdown using an `AbortController`. The main difference is that `shutdown` can be awaited to know when the shutdown routine has run to completion.\n\n```ts\nconst abortController = new AbortController();\n\nvoid watch({\n  abortController,\n  project: __dirname,\n  triggers: [\n    {\n      name: 'test',\n      expression: ['match', '*', 'basename'],\n      onChange: async ({ spawn }) =\u003e {\n        // `sleep 60` will receive `SIGTERM` as soon as `shutdown()` is called.\n        await spawn`sleep 60`;\n      },\n    }\n  ],\n});\n\nvoid abortController.abort();\n```\n\n### Handling the `AbortSignal`\n\nWorkflow might be interrupted in two scenarios:\n\n* when Turbowatch is being gracefully shutdown\n* when routine is marked as `interruptible` and a new file change is detected\n\nImplementing interruptible workflows requires that you define `AbortSignal` handler. If you are using [`zx`](https://npmjs.com/zx), such abstraction could look like so:\n\n\u003e **Note** Turbowatch already comes with [`zx`](https://npmjs.com/zx) bound to the `AbortSignal`. Just use `spawn`. Documentation demonstrates how to implement equivalent functionality.\n\n```ts\nimport { type ProcessPromise } from 'zx';\n\nconst interrupt = async (\n  processPromise: ProcessPromise,\n  abortSignal: AbortSignal,\n) =\u003e {\n  let aborted = false;\n\n  const kill = () =\u003e {\n    aborted = true;\n\n    processPromise.kill();\n  };\n\n  abortSignal.addEventListener('abort', kill, { once: true });\n\n  try {\n    await processPromise;\n  } catch (error) {\n    if (!aborted) {\n      console.log(error);\n    }\n  }\n\n  abortSignal.removeEventListener('abort', kill);\n};\n```\n\nwhich you can then use to kill your scripts, e.g.\n\n```ts\nexport default watch({\n  project: __dirname,\n  triggers: [\n    {\n      expression: ['match', '*.ts', 'basename'],\n      interruptible: false,\n      name: 'sleep',\n      onChange: async ({ abortSignal }) =\u003e {\n        await interrupt($`sleep 30`, abortSignal);\n      },\n    },\n  ],\n});\n```\n\n### Tearing down project\n\n`onTeardown` is going to be called when Turbowatch is gracefully terminated. Use it to \"clean up\" the project if necessary.\n\n\u003e **Warning** There is no timeout for `onTeardown`.\n\n```ts\nimport { watch } from 'turbowatch';\n\nexport default watch({\n  abortController,\n  project: __dirname,\n  triggers: [\n    {\n      expression: ['match', '*.ts', 'basename'],\n      name: 'build',\n      onChange: async ({ spawn }) =\u003e {\n        await spawn`tsc`;\n      },\n      onTeardown: async () =\u003e {\n        await spawn`rm -fr ./dist`;\n      },\n    },\n  ],\n});\n```\n\n### Throttling `spawn` output\n\nWhen multiple processes are sending logs in parallel, the log stream might be hard to read, e.g.\n\n```yaml\nredis:dev: 973191cf \u003e #5 sha256:7f65636102fd1f499092cb075baa95784488c0bbc3e0abff2a6d853109e4a948 4.19MB / 9.60MB 22.3s\napi:dev: a1e4c6a7 \u003e [18:48:37.171] 765ms debug @utilities #waitFor: Waiting for database to be ready...\nredis:dev: 973191cf \u003e #5 sha256:d01ec855d06e16385fb33f299d9cc6eb303ea04378d0eea3a75d74e26c6e6bb9 0B / 1.39MB 22.7s\napi:dev: a1e4c6a7 \u003e [18:48:37.225]  54ms debug @utilities #waitFor: Waiting for Redis to be ready...\nworker:dev: 2fb02d72 \u003e [18:48:37.313]  88ms debug @utilities #waitFor: Waiting for database to be ready...\nredis:dev: 973191cf \u003e #5 sha256:7f65636102fd1f499092cb075baa95784488c0bbc3e0abff2a6d853109e4a948 5.24MB / 9.60MB 22.9s\nworker:dev: 2fb02d72 \u003e [18:48:37.408]  95ms debug @utilities #waitFor: Waiting for Redis to be ready...\nredis:dev: 973191cf \u003e #5 sha256:7f65636102fd1f499092cb075baa95784488c0bbc3e0abff2a6d853109e4a948 6.29MB / 9.60MB 23.7s\napi:dev: a1e4c6a7 \u003e [18:48:38.172] 764ms debug @utilities #waitFor: Waiting for database to be ready...\napi:dev: a1e4c6a7 \u003e [18:48:38.227]  55ms debug @utilities #waitFor: Waiting for Redis to be ready...\n```\n\nIn this example, `redis`, `api` and `worker` processes produce logs at almost the exact same time causing the log stream to switch between outputting from a different process every other line. This makes it hard to read the logs.\n\nBy default, Turbowatch throttles log output to at most once a second per task, producing a lot more easier to follow log output:\n\n```yaml\nredis:dev: 973191cf \u003e #5 sha256:7f65636102fd1f499092cb075baa95784488c0bbc3e0abff2a6d853109e4a948 4.19MB / 9.60MB 22.3s\nredis:dev: 973191cf \u003e #5 sha256:d01ec855d06e16385fb33f299d9cc6eb303ea04378d0eea3a75d74e26c6e6bb9 0B / 1.39MB 22.7s\nredis:dev: 973191cf \u003e #5 sha256:7f65636102fd1f499092cb075baa95784488c0bbc3e0abff2a6d853109e4a948 5.24MB / 9.60MB 22.9s\nredis:dev: 973191cf \u003e #5 sha256:7f65636102fd1f499092cb075baa95784488c0bbc3e0abff2a6d853109e4a948 6.29MB / 9.60MB 23.7s\napi:dev: a1e4c6a7 \u003e [18:48:37.171] 765ms debug @utilities #waitFor: Waiting for database to be ready...\napi:dev: a1e4c6a7 \u003e [18:48:37.225]  54ms debug @utilities #waitFor: Waiting for Redis to be ready...\napi:dev: a1e4c6a7 \u003e [18:48:38.172] 764ms debug @utilities #waitFor: Waiting for database to be ready...\napi:dev: a1e4c6a7 \u003e [18:48:38.227]  55ms debug @utilities #waitFor: Waiting for Redis to be ready...\nworker:dev: 2fb02d72 \u003e [18:48:37.313]  88ms debug @utilities #waitFor: Waiting for database to be ready...\nworker:dev: 2fb02d72 \u003e [18:48:37.408]  95ms debug @utilities #waitFor: Waiting for Redis to be ready...\n```\n\nHowever, this means that some logs might come out of order. To disable this feature, set `{ throttleOutput: { delay: 0 } }`.\n\n### Watching multiple scripts\n\nBy default, `turbowatch` will look for `turbowatch.ts` script in the current working directory. However, you can pass multiple scripts to `turbowatch` to run them concurrently:\n\n```bash\nturbowatch ./foo.ts ./bar.ts\n```\n\nYou can also provide a glob pattern:\n\n```bash\nturbowatch '**/turbowatch.ts'\n```\n\n### Using custom file watching backend\n\nMany of the existing file watching solutions come with tradeoffs, e.g. Watchman does not track symbolic links ([#105](https://github.com/facebook/watchman/issues/105#issuecomment-1469496330)), chokidar is failing to register file changes ([#1240](https://github.com/paulmillr/chokidar/issues/1240)), `fs.watch` behavior is platform specific, etc. For this reason, Turbowatch provides several backends to choose from and allows to bring-your-own backend by implementing `FileWatchingBackend` interface.\n\nBy default, Turbowatch uses `fs.watch` on MacOS (Node.js v19.1+) and fallsback to [chokidar](https://github.com/paulmillr/chokidar) on other platforms.\n\n```ts\nimport {\n  watch,\n  // Smart Watcher that detects the best available file-watching backend.\n  TurboWatcher,\n  // fs.watch based file watcher.\n  FSWatcher,\n  // Chokidar based file watcher.\n  ChokidarWatcher,\n  // Interface that all file watchers must implement.\n  FileWatchingBackend,\n} from 'turbowatch';\n\nexport default watch({\n  Watcher: TurboWatcher,\n  project: __dirname,\n  triggers: [],\n});\n```\n\n### Logging\n\nTurbowatch uses [Roarr](https://github.com/gajus/roarr) logger.\n\nExport `ROARR_LOG=true` environment variable to enable log printing to `stdout`.\n\nUse [@roarr/cli](https://github.com/gajus/roarr-cli) to pretty-print logs.\n\n```bash\nROARR_LOG=true turbowatch | roarr\n```\n\n## Experiments\n\nThese are features that are available behind feature flags (`TURBOWATCH_EXPERIMENTAL_*`).\n\nThey are released to gather community feedback and may change at any point in future.\n\n\u003e **Note** There are no active experiments at the moment.\n\n## Alternatives\n\nThe biggest benefit of using Turbowatch is that it provides a single abstraction for all file watching operations. That is, you might get away with Nodemon, concurrently, `--watch`, etc. running in parallel, but using Turbowatch will introduce consistency to how you perform watch operations.\n\n### Why not use `X --watch`?\n\nMany tools provide built-in watch functionality, e.g. `tsc --watch`. However, there are couple of problems with relying on them:\n\n* Running many file watchers is inefficient and is probably draining your laptop's battery faster than you realize. Turbowatch uses a single server to watch all file changes.\n* Native tools do not allow to combine operations, e.g. If your build depends on `tsc --watch` and `tsc-alias --watch`, then you cannot combine them. On the other hand, Turbowatch allows you to chain arbitrary operations.\n\n\u003e **Note** Turbowatch is not a replacement for services that implement Hot Module Replacement (HMR), e.g. Next.js. However, you should still wrap those operations in Turbowatch for consistency, e.g.\n\u003e ```ts\n\u003e void watch({\n\u003e   project: __dirname,\n\u003e   triggers: [\n\u003e     {\n\u003e       expression: ['dirname', __dirname],\n\u003e       // Marking this routine as non-interruptible will ensure that\n\u003e       // next dev is not restarted when file changes are detected.\n\u003e       interruptible: false,\n\u003e       name: 'start-server',\n\u003e       onChange: async ({ spawn }) =\u003e {\n\u003e         await spawn`next dev`;\n\u003e       },\n\u003e       // Enabling this option modifies what Turbowatch logs and warns\n\u003e       // you if your configuration is incompatible with persistent tasks.\n\u003e       persistent: true,\n\u003e     },\n\u003e   ],\n\u003e });\n\u003e ```\n\n### Why not concurrently?\n\nI have [seen](https://github.com/justkey007/tsc-alias#add-it-to-your-build-scripts-in-packagejson) [concurrently](https://github.com/open-cli-tools/concurrently) used to \"chain\" watch operations such as:\n\n```bash\nconcurrently \"tsc -w\" \"tsc-alias -w\"\n```\n\nWhile this might work by brute-force, it will produce unexpected results as the order of execution is not guaranteed.\n\nIf you are using Turbowatch, simply execute one command after the other in the trigger workflow, e.g.\n\n```ts\nasync ({ spawn }: ChangeEvent) =\u003e {\n  await spawn`tsc`;\n  await spawn`tsc-alias`;\n},\n```\n\n### Why not Turborepo?\n\n[Turborepo](https://turbo.build/) currently does not have support for watch mode (issue [#986](https://github.com/vercel/turbo/issues/986)). However, Turbowatch has been designed to work with Turborepo.\n\nTo use Turbowatch with Turborepo:\n\n1. define a persistent task\n1. run the persistent task using `--parallel`\n\nExample:\n\n```json\n\"dev\": {\n  \"cache\": false,\n  \"persistent\": true\n},\n```\n\n```bash\nturbo run dev --parallel\n```\n\n\u003e **Note** We found that using `dependsOn` with Turbowatch produces undesirable effects. Instead, simply use Turbowatch expressions to identify when dependencies update.\n\n\u003e **Note** Turbowatch is not aware of the Turborepo dependency graph. Meaning, that your builds might fail at the first attempt. However, if you setup Turbowatch to [watch `node_modules`](#watching-node_modules), then Turbowatch will automatically retry failing builds as soon as the dependencies are built.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgajus%2Fturbowatch","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fgajus%2Fturbowatch","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fgajus%2Fturbowatch/lists"}