diff --git a/src/content/pages/de/advanced/best-practice-performance.md b/src/content/pages/de/advanced/best-practice-performance.md index 615d160130..b733776504 100644 --- a/src/content/pages/de/advanced/best-practice-performance.md +++ b/src/content/pages/de/advanced/best-practice-performance.md @@ -41,7 +41,7 @@ const app = express(); app.use(compression()); ``` -Für eine stark frequentierte Website in der Produktion, der beste Weg zur Komprimierung ist die Implementierung auf umgekehrter Proxyebene (siehe [Reverse Proxy](#use-a-reverse-proxy)) . In diesem Fall brauchen Sie keine Komprimierungsmittelware. Details zum Aktivieren der gzip-Komprimierung in Nginx finden Sie unter [Module ngx_http_gzip_module](http://nginx.org/en/docs/http/ngx_http_gzip_module) in der Nginx-Dokumentation. +Für eine stark frequentierte Website in der Produktion, der beste Weg zur Komprimierung ist die Implementierung auf umgekehrter Proxyebene (siehe [Reverse Proxy](#use-a-reverse-proxy)) . In diesem Fall brauchen Sie keine Komprimierungsmittelware. Details zum Aktivieren der gzip-Komprimierung in Nginx finden Sie unter [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) in der Nginx-Dokumentation. ### Keine synchronen Funktionen verwenden @@ -49,11 +49,11 @@ Synchronische Funktionen und Methoden binden den Ausführungsprozess bis sie zur Obwohl Node und viele Module synchrone und asynchrone Versionen ihrer Funktionen liefern, verwenden Sie immer die asynchrone Version in der Produktion. Die einzige Zeit, in der eine synchrone Funktion gerechtfertigt werden kann, ist beim ersten Start. -Du kannst das `--trace-sync-io` Kommandozeilen-Flag verwenden, um eine Warnung und einen Stack-Trace zu drucken, wann immer deine Anwendung eine synchrone API verwendet. Natürlich möchten Sie dies nicht in der Produktion verwenden, sondern vielmehr sicherstellen, dass Ihr Code produktionsbereit ist. Weitere Informationen finden Sie in der [Knoten Kommandozeilenoptionen Dokumentation](https://nodejs.org/api/cli#cli_trace_sync_io) . +Du kannst das `--trace-sync-io` Kommandozeilen-Flag verwenden, um eine Warnung und einen Stack-Trace zu drucken, wann immer deine Anwendung eine synchrone API verwendet. Natürlich möchten Sie dies nicht in der Produktion verwenden, sondern vielmehr sicherstellen, dass Ihr Code produktionsbereit ist. Weitere Informationen finden Sie in der [Knoten Kommandozeilenoptionen Dokumentation](https://nodejs.org/api/cli.html#trace-sync-io) . ### Logging korrekt -Im Allgemeinen gibt es zwei Gründe für die Protokollierung aus Ihrer App: Für das Debuggen und für die Protokollierung von App-Aktivitäten (im Wesentlichen alles andere). Die Verwendung von `console.log()` oder `console.error()` zum Drucken von Logmeldungen an das Terminal ist gängige Praxis in der Entwicklung. Aber [diese Funktionen sind synchronisiert](https://nodejs.org/api/console#console), wenn das Ziel ein Terminal oder eine Datei ist so dass sie nicht für die Produktion geeignet sind, es sei denn, Sie rollen die Ausgabe zu einem anderen Programm. +Im Allgemeinen gibt es zwei Gründe für die Protokollierung aus Ihrer App: Für das Debuggen und für die Protokollierung von App-Aktivitäten (im Wesentlichen alles andere). Die Verwendung von `console.log()` oder `console.error()` zum Drucken von Logmeldungen an das Terminal ist gängige Praxis in der Entwicklung. Aber [diese Funktionen sind synchronisiert](https://nodejs.org/api/console.html), wenn das Ziel ein Terminal oder eine Datei ist so dass sie nicht für die Produktion geeignet sind, es sei denn, Sie rollen die Ausgabe zu einem anderen Programm. #### Zum Debuggen @@ -134,9 +134,9 @@ Best Practices ist es, Fehler so nah wie möglich an der Website zu behandeln. S Eine Sache, die du _nicht_ tun solltest ist, auf das `uncaptException` Event zu hören emittiert, wenn eine Ausnahme den ganzen Weg zurück zur Ereignis-Schleife weht. Das Hinzufügen eines Ereignis-Listeners für `uncaughtException` ändert das Standardverhalten des Prozesses, der auf eine Ausnahme stößt; wird der Prozess trotz der Ausnahme weiterhin laufen. Dies könnte nach einer guten Möglichkeit klingen, um zu verhindern, dass Ihre App abstürzt, aber die Anwendung nach einer nicht gefangenen Ausnahme weiterhin zu laufen ist eine gefährliche Praxis und wird nicht empfohlen, weil der Zustand des Prozesses unzuverlässig und unberechenbar wird. -Zusätzlich wird die Verwendung von `uncaughtException` offiziell als [crude]anerkannt (https://nodejs.org/api/process#process_event_uncaughtexception). Also ist das Hören auf `uncaughtException` eine schlechte Idee. Aus diesem Grund empfehlen wir Dinge wie mehrere Prozesse und Supervisoren: Absturz und Neustart sind oft der zuverlässigste Weg, um einen Fehler zu beheben. +Zusätzlich wird die Verwendung von `uncaughtException` offiziell als [crude]anerkannt (https://nodejs.org/api/process.html#event-uncaughtexception). Also ist das Hören auf `uncaughtException` eine schlechte Idee. Aus diesem Grund empfehlen wir Dinge wie mehrere Prozesse und Supervisoren: Absturz und Neustart sind oft der zuverlässigste Weg, um einen Fehler zu beheben. -Wir empfehlen auch nicht [domains]zu verwenden (https://nodejs.org/api/domain). Es löst das Problem im Allgemeinen nicht und ist ein veraltetes Modul. +Wir empfehlen auch nicht [domains]zu verwenden (https://nodejs.org/api/domain.html). Es löst das Problem im Allgemeinen nicht und ist ein veraltetes Modul. ## Dinge zu tun in Ihrer Umgebung / Einrichtung @@ -240,7 +240,7 @@ Restart=always WantedBy=multi-user.target ``` -Weitere Informationen zum System finden Sie unter [systemd reference (man page)](http://www.freedesktop.org/software/systemd/man/systemd.unit). +Weitere Informationen zum System finden Sie unter [systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/index.html). ### Starte deine App in einem Cluster @@ -254,7 +254,7 @@ In geclusterten Apps können Worker-Prozesse individuell abstürzen, ohne den Re #### Cluster-Modul des Knotens -Clustering wird mit Knotens [Cluster-Modul](https://nodejs.org/api/cluster) ermöglicht. Dies ermöglicht es einem Master-Prozess, Worker-Prozesse zu generieren und eingehende Verbindungen unter den Arbeitern zu verteilen. +Clustering wird mit Knotens [Cluster-Modul](https://nodejs.org/api/cluster.html) ermöglicht. Dies ermöglicht es einem Master-Prozess, Worker-Prozesse zu generieren und eingehende Verbindungen unter den Arbeitern zu verteilen. #### PM2 verwenden @@ -294,7 +294,7 @@ Benutze einen Caching-Server wie [Varnish](https://www.varnish-cache.org/) oder Egal wie optimiert eine App ist, eine einzelne Instanz kann nur eine begrenzte Menge an Last und Traffic verwalten. Eine Möglichkeit, eine App zu skalieren, besteht darin, mehrere Instanzen davon auszuführen und den Traffic über einen Lastausgleicher zu verteilen. Das Einrichten eines Lastausgleichs kann die Leistung und Geschwindigkeit Ihrer App verbessern und es ermöglichen, mehr zu skalieren, als mit einer einzigen Instanz möglich ist. -Ein Loadbalancer ist in der Regel ein Reverse-Proxy, der den Datenverkehr zu und von mehreren Anwendungsinstanzen und Servern regelt. Mit [Nginx](https://nginx.org/en/docs/http/load_balancing) oder [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts) können Sie ganz einfach einen Lastausgleich für Ihre App einrichten. +Ein Loadbalancer ist in der Regel ein Reverse-Proxy, der den Datenverkehr zu und von mehreren Anwendungsinstanzen und Servern regelt. Mit [Nginx](https://nginx.org/en/docs/http/load_balancing.html) oder [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts) können Sie ganz einfach einen Lastausgleich für Ihre App einrichten. Bei Loadbalancing müssen Sie eventuell sicherstellen, dass Anforderungen, die mit einer bestimmten Session-ID in Verbindung stehen, mit dem Prozess verbunden sind, der sie verursacht hat. Dies ist _session_, oder _sticky sessions_, bekannt und kann durch den oben genannten Vorschlag angesprochen werden, um einen Datenspeicher wie Redis für Sitzungsdaten (je nach Anwendung) zu verwenden. Für eine Diskussion siehe [Mehrere Knoten verwenden](https://socket.io/docs/v4/using-multiple-nodes/). diff --git a/src/content/pages/en/advanced/best-practice-performance.md b/src/content/pages/en/advanced/best-practice-performance.md index a98c7fcf6a..22e8498551 100644 --- a/src/content/pages/en/advanced/best-practice-performance.md +++ b/src/content/pages/en/advanced/best-practice-performance.md @@ -41,7 +41,7 @@ const app = express(); app.use(compression()); ``` -For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](http://nginx.org/en/docs/http/ngx_http_gzip_module) in the Nginx documentation. +For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation. ### Don't use synchronous functions @@ -49,11 +49,11 @@ Synchronous functions and methods tie up the executing process until they return Although Node and many modules provide synchronous and asynchronous versions of their functions, always use the asynchronous version in production. The only time when a synchronous function can be justified is upon initial startup. -You can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli#cli_trace_sync_io) for more information. +You can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli.html#trace-sync-io) for more information. ### Do logging correctly -In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console#console) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program. +In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console.html) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program. #### For debugging @@ -134,9 +134,9 @@ Best practice is to handle errors as close to the site as possible. So while thi One thing you should _not_ do is to listen for the `uncaughtException` event, emitted when an exception bubbles all the way back to the event loop. Adding an event listener for `uncaughtException` will change the default behavior of the process that is encountering an exception; the process will continue to run despite the exception. This might sound like a good way of preventing your app from crashing, but continuing to run the app after an uncaught exception is a dangerous practice and is not recommended, because the state of the process becomes unreliable and unpredictable. -Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process#process_event_uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error. +Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process.html#event-uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error. -We also don't recommend using [domains](https://nodejs.org/api/domain). It generally doesn't solve the problem and is a deprecated module. +We also don't recommend using [domains](https://nodejs.org/api/domain.html). It generally doesn't solve the problem and is a deprecated module. ## Things to do in your environment / setup @@ -240,7 +240,7 @@ Restart=always WantedBy=multi-user.target ``` -For more information on systemd, see the [systemd reference (man page)](http://www.freedesktop.org/software/systemd/man/systemd.unit). +For more information on systemd, see the [systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/index.html). ### Run your app in a cluster @@ -254,7 +254,7 @@ In clustered apps, worker processes can crash individually without affecting the #### Using Node's cluster module -Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster). This enables a master process to spawn worker processes and distribute incoming connections among the workers. +Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). This enables a master process to spawn worker processes and distribute incoming connections among the workers. #### Using PM2 @@ -294,7 +294,7 @@ Use a caching server like [Varnish](https://www.varnish-cache.org/) or [Nginx](h No matter how optimized an app is, a single instance can handle only a limited amount of load and traffic. One way to scale an app is to run multiple instances of it and distribute the traffic via a load balancer. Setting up a load balancer can improve your app's performance and speed, and enable it to scale more than is possible with a single instance. -A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](https://nginx.org/en/docs/http/load_balancing) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). +A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](https://nginx.org/en/docs/http/load_balancing.html) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). With load balancing, you might have to ensure that requests that are associated with a particular session ID connect to the process that originated them. This is known as _session affinity_, or _sticky sessions_, and may be addressed by the suggestion above to use a data store such as Redis for session data (depending on your application). For a discussion, see [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/). diff --git a/src/content/pages/es/advanced/best-practice-performance.md b/src/content/pages/es/advanced/best-practice-performance.md index 575a6a97d8..110d88d9a4 100644 --- a/src/content/pages/es/advanced/best-practice-performance.md +++ b/src/content/pages/es/advanced/best-practice-performance.md @@ -41,7 +41,7 @@ const app = express(); app.use(compression()); ``` -Para un sitio web de alto tráfico en producción, la mejor manera de poner compresión en su lugar es implementarla en un nivel proxy inverso (ver [Usar un proxy inverso](#use-a-reverse-proxy)). En ese caso, no necesita usar middleware de compresión. Para más detalles sobre habilitar compresión gzip en Nginx, vea [Módulo ngx_http_gzip_module](http://nginx.org/en/docs/http/ngx_http_gzip_module) en la documentación de Nginx. +Para un sitio web de alto tráfico en producción, la mejor manera de poner compresión en su lugar es implementarla en un nivel proxy inverso (ver [Usar un proxy inverso](#use-a-reverse-proxy)). En ese caso, no necesita usar middleware de compresión. Para más detalles sobre habilitar compresión gzip en Nginx, vea [Módulo ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) en la documentación de Nginx. ### No utilizar funciones sincrónicas @@ -49,11 +49,11 @@ Las funciones y métodos sincrónicos emiten el proceso de ejecución hasta que Aunque Node y muchos módulos proporcionan versiones sincrónicas y asíncronas de sus funciones, siempre utiliza la versión asíncrona en producción. La única vez que una función sincrónica puede ser justificada es al inicio inicial. -Puedes usar la bandera de línea de comandos `--trace-sync-io` para imprimir una advertencia y un stack trace cada vez que tu aplicación usa una API sincrónica. Por supuesto, no querrías usar esto en la producción, sino más bien asegurar que tu código esté listo para la producción. Vea la [documentación de opciones de línea de comandos de nodo](https://nodejs.org/api/cli#cli_trace_sync_io) para más información. +Puedes usar la bandera de línea de comandos `--trace-sync-io` para imprimir una advertencia y un stack trace cada vez que tu aplicación usa una API sincrónica. Por supuesto, no querrías usar esto en la producción, sino más bien asegurar que tu código esté listo para la producción. Vea la [documentación de opciones de línea de comandos de nodo](https://nodejs.org/api/cli.html#trace-sync-io) para más información. ### Hacer el registro correctamente -En general, hay dos razones para registrarse desde tu aplicación: para depurar y para registrar la actividad de la aplicación (esencialmente, todo lo demás). Usar `console.log()` o `console.error()` para imprimir mensajes de registro en la terminal es práctica común en desarrollo. Pero [estas funciones son sincrónicas](https://nodejs.org/api/console#console) cuando el destino es un terminal o un archivo, por lo que no son aptos para la producción, a menos que usted pipe la salida a otro programa. +En general, hay dos razones para registrarse desde tu aplicación: para depurar y para registrar la actividad de la aplicación (esencialmente, todo lo demás). Usar `console.log()` o `console.error()` para imprimir mensajes de registro en la terminal es práctica común en desarrollo. Pero [estas funciones son sincrónicas](https://nodejs.org/api/console.html) cuando el destino es un terminal o un archivo, por lo que no son aptos para la producción, a menos que usted pipe la salida a otro programa. #### Para depuración @@ -134,9 +134,9 @@ La mejor práctica es manejar los errores lo más cerca posible del sitio. Así Una cosa que debes _no_ hacer es escuchar el evento `uncaughtException`, emitido cuando una excepción emite todo el camino de regreso al bucle del evento. Añadir un detector de eventos para `uncaughtException` cambiará el comportamiento predeterminado del proceso que se encuentra con una excepción; el proceso continuará funcionando a pesar de la excepción. Esto puede sonar como una buena manera de evitar que tu aplicación falle, pero seguir ejecutando la aplicación después de una excepción no capturada es una práctica peligrosa y no se recomienda, porque el estado del proceso se vuelve poco fiable e impredecible. -Además, usar `uncaughtException` es oficialmente reconocido como [crude](https://nodejs.org/api/process#process_event_uncaughtexception). Así que escuchar `uncaughtException` es sólo una mala idea. Por eso recomendamos cosas como múltiples procesos y supervisores: fallar y reiniciar es a menudo la manera más confiable de recuperarse de un error. +Además, usar `uncaughtException` es oficialmente reconocido como [crude](https://nodejs.org/api/process.html#event-uncaughtexception). Así que escuchar `uncaughtException` es sólo una mala idea. Por eso recomendamos cosas como múltiples procesos y supervisores: fallar y reiniciar es a menudo la manera más confiable de recuperarse de un error. -Tampoco recomendamos usar [domains](https://nodejs.org/api/domain). Generalmente no resuelve el problema y es un módulo obsoleto. +Tampoco recomendamos usar [domains](https://nodejs.org/api/domain.html). Generalmente no resuelve el problema y es un módulo obsoleto. ## Cosas que hacer en tu entorno / configuración @@ -240,7 +240,7 @@ Restart=always WantedBy=multi-user.target ``` -Para más información sobre el sistema, vea la [referencia del sistema (página de manu)] (http://www.freedesktop.org/software/systemd/man/systemd.unit). +Para más información sobre el sistema, vea la [referencia del sistema (página de manu)] (https://www.freedesktop.org/software/systemd/man/latest/index.html). ### Ejecutar tu aplicación en un clúster @@ -254,7 +254,7 @@ En las aplicaciones agrupadas, los procesos del worker pueden fallar individualm #### Usando el módulo de cluster del nodo -Clustering es posible con el [módulo de cluster]de Node (https://nodejs.org/api/cluster). Esto permite que un proceso maestro genere procesos de trabajador y distribuya conexiones entrantes entre los trabajadores. +Clustering es posible con el [módulo de cluster]de Node (https://nodejs.org/api/cluster.html). Esto permite que un proceso maestro genere procesos de trabajador y distribuya conexiones entrantes entre los trabajadores. #### Usando PM2 @@ -294,7 +294,7 @@ Usa un servidor de caché como [Varnish](https://www.varnish-cache.org/) o [Ngin No importa cuán optimizada sea una aplicación, una sola instancia puede manejar sólo una cantidad limitada de carga y tráfico. Una forma de escalar una aplicación es ejecutar múltiples instancias de ella y distribuir el tráfico a través de un equilibrador de carga. Configurar un balanceador de carga puede mejorar el rendimiento y la velocidad de tu aplicación, y permitirla escalar más de lo posible con una sola instancia. -Un balanceador de carga es generalmente un proxy inverso que orchestriza tráfico hacia y desde múltiples instancias y servidores de la aplicación. Puedes configurar fácilmente un equilibrador de carga para tu aplicación usando [Nginx](https://nginx.org/en/docs/http/load_balancing) o [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). +Un balanceador de carga es generalmente un proxy inverso que orchestriza tráfico hacia y desde múltiples instancias y servidores de la aplicación. Puedes configurar fácilmente un equilibrador de carga para tu aplicación usando [Nginx](https://nginx.org/en/docs/http/load_balancing.html) o [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). Con el saldo de carga, puede que tenga que asegurarse de que las peticiones que están asociadas con un ID de sesión particular se conectan al proceso que las originó. Esto se conoce como _session affinity_, o _sticky sessions_, y puede ser abordado por la sugerencia anterior de utilizar un almacén de datos como Redis para datos de sesión (dependiendo de su aplicación). Para una discusión, vea [Usando múltiples nodos](https://socket.io/docs/v4/using-multiple-nodes/). diff --git a/src/content/pages/fr/advanced/best-practice-performance.md b/src/content/pages/fr/advanced/best-practice-performance.md index 70525e8e1f..4bb38e4db3 100644 --- a/src/content/pages/fr/advanced/best-practice-performance.md +++ b/src/content/pages/fr/advanced/best-practice-performance.md @@ -41,7 +41,7 @@ const app = express(); app.use(compression()); ``` -Pour un site internet à fort trafic en production, la meilleure façon de mettre en place une compression est de l'implémenter à un niveau de proxy inverse (voir [Utiliser un proxy inverse](#use-a-reverse-proxy)). Dans ce cas, vous n'avez pas besoin d'utiliser le middleware de compression. Pour plus de détails sur l'activation de la compression gzip dans Nginx, voir [Module ngx_http_gzip_module](http://nginx.org/en/docs/http/ngx_http_gzip_module) dans la documentation Nginx. +Pour un site internet à fort trafic en production, la meilleure façon de mettre en place une compression est de l'implémenter à un niveau de proxy inverse (voir [Utiliser un proxy inverse](#use-a-reverse-proxy)). Dans ce cas, vous n'avez pas besoin d'utiliser le middleware de compression. Pour plus de détails sur l'activation de la compression gzip dans Nginx, voir [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) dans la documentation Nginx. ### Ne pas utiliser les fonctions synchrones @@ -49,11 +49,11 @@ Les fonctions et méthodes synchrones lient le processus d'exécution jusqu'à c Bien que Node et de nombreux modules fournissent des versions synchrones et asynchrones de leurs fonctions, utilisez toujours la version asynchrone en production. Le seul moment où une fonction synchrone peut être justifiée est au démarrage initial. -Vous pouvez utiliser le flag en ligne de commande `--trace-sync-io` pour afficher une alerte et une trace de pile chaque fois que votre application utilise une API synchrone. Bien sûr, vous ne voudriez pas utiliser cela en production, mais plutôt vous assurer que votre code est prêt pour la production. Voir la [documentation des options de la ligne de commande node](https://nodejs.org/api/cli#cli_trace_sync_io) pour plus d'informations. +Vous pouvez utiliser le flag en ligne de commande `--trace-sync-io` pour afficher une alerte et une trace de pile chaque fois que votre application utilise une API synchrone. Bien sûr, vous ne voudriez pas utiliser cela en production, mais plutôt vous assurer que votre code est prêt pour la production. Voir la [documentation des options de la ligne de commande node](https://nodejs.org/api/cli.html#trace-sync-io) pour plus d'informations. ### Faire la journalisation correctement -En général, il y a deux raisons de se connecter depuis votre application : pour le débogage et pour l'activité des applications de journalisation (essentiellement tout le reste). Utiliser `console.log()` ou `console.error()` pour imprimer les messages de log vers le terminal est pratique courante dans le développement. Mais [ces fonctions sont synchronisées] (https://nodejs.org/api/console#console) lorsque la destination est un terminal ou un fichier, elles ne sont donc pas adaptées à la production, à moins que vous ne conduisiez la sortie vers un autre programme. +En général, il y a deux raisons de se connecter depuis votre application : pour le débogage et pour l'activité des applications de journalisation (essentiellement tout le reste). Utiliser `console.log()` ou `console.error()` pour imprimer les messages de log vers le terminal est pratique courante dans le développement. Mais [ces fonctions sont synchronisées] (https://nodejs.org/api/console.html) lorsque la destination est un terminal ou un fichier, elles ne sont donc pas adaptées à la production, à moins que vous ne conduisiez la sortie vers un autre programme. #### Pour le débogage @@ -134,9 +134,9 @@ La meilleure pratique est de gérer les erreurs le plus près possible du site. Une chose que vous ne devriez pas _faire_ est d'écouter l'évènement `uncatghtException` émise lorsqu'une exception bulle tout le retour à la boucle d'événement. Ajouter un event listener pour `uncatghtException` changera le comportement par défaut du processus qui rencontre une exception ; le processus continuera à fonctionner malgré l'exception. Cela peut sembler un bon moyen d'empêcher votre application de planter, mais continuer à exécuter l'application après une exception non capturée est une pratique dangereuse et n'est pas recommandé, parce que l'état du processus devient peu fiable et imprévisible. -De plus, l'utilisation de `uncaughtException` est officiellement reconnue comme [crude](https://nodejs.org/api/process#process_event_uncaughtexception). Donc l'écoute de `uncatghtException` est juste une mauvaise idée. C'est pourquoi nous recommandons des choses comme des processus multiples et des superviseurs : plantage et redémarrage est souvent le moyen le plus fiable de se remettre d'une erreur. +De plus, l'utilisation de `uncaughtException` est officiellement reconnue comme [crude](https://nodejs.org/api/process.html#event-uncaughtexception). Donc l'écoute de `uncatghtException` est juste une mauvaise idée. C'est pourquoi nous recommandons des choses comme des processus multiples et des superviseurs : plantage et redémarrage est souvent le moyen le plus fiable de se remettre d'une erreur. -Nous ne recommandons pas non plus d'utiliser [domains](https://nodejs.org/api/domain). Il ne résout généralement pas le problème et est un module obsolète. +Nous ne recommandons pas non plus d'utiliser [domains](https://nodejs.org/api/domain.html). Il ne résout généralement pas le problème et est un module obsolète. ## Choses à faire dans votre environnement / configuration @@ -240,7 +240,7 @@ Restart=always WantedBy=multi-user.target ``` -Pour plus d'informations sur le système, voir [systemd reference (man page)] (http://www.freedesktop.org/software/systemd/man/systemd.unit). +Pour plus d'informations sur le système, voir [systemd reference (man page)] (https://www.freedesktop.org/software/systemd/man/latest/index.html). ### Exécutez votre application dans un cluster @@ -254,7 +254,7 @@ Dans les applications groupées, les processus de travail peuvent planter indivi #### Utilisation du module de cluster de Node -Le groupement est rendu possible avec le [module de clustage] (https://nodejs.org/api/cluster). Cela permet à un processus maître de faire apparaître des processus de travail et de distribuer des connexions entrantes entre les travailleurs. +Le groupement est rendu possible avec le [module de clustage] (https://nodejs.org/api/cluster.html). Cela permet à un processus maître de faire apparaître des processus de travail et de distribuer des connexions entrantes entre les travailleurs. #### Utilisation du PM2 @@ -294,7 +294,7 @@ Utilisez un serveur de cache comme [Varnish](https://www.varnish-cache.org/) ou Quelle que soit l'optimisation d'une application, une seule instance ne peut gérer qu'une quantité limitée de charge et de trafic. Une façon de mettre à l'échelle une application est d'exécuter plusieurs instances et de distribuer le trafic via un répartiteur de charge. La mise en place d'un répartiteur de charge peut améliorer les performances et la vitesse de votre application et l'activer pour augmenter la taille de votre système par une seule instance. -Un répartiteur de charge est généralement un mandataire inversé qui orchestre le trafic entre et à partir de plusieurs instances et serveurs d'applications. Vous pouvez facilement configurer un répartiteur de charge pour votre application en utilisant [Nginx](https://nginx.org/en/docs/http/load_balancing) ou [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). +Un répartiteur de charge est généralement un mandataire inversé qui orchestre le trafic entre et à partir de plusieurs instances et serveurs d'applications. Vous pouvez facilement configurer un répartiteur de charge pour votre application en utilisant [Nginx](https://nginx.org/en/docs/http/load_balancing.html) ou [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). Avec l'équilibrage de charge, vous devrez peut-être vous assurer que les requêtes qui sont associées à un ID de session particulier se connectent au processus qui les a originés. C'est connu sous le nom _affinity_, ou _sticky sessions_, et peut être adressé par la suggestion ci-dessus d'utiliser un stockage de données tel que Redis pour les données de session (selon votre application). Pour une discussion, voir [Utilisation de plusieurs nœuds](https://socket.io/docs/v4/using-multiple-nodes/). diff --git a/src/content/pages/it/advanced/best-practice-performance.md b/src/content/pages/it/advanced/best-practice-performance.md index c0a8ac9a9c..74239aa57a 100644 --- a/src/content/pages/it/advanced/best-practice-performance.md +++ b/src/content/pages/it/advanced/best-practice-performance.md @@ -41,7 +41,7 @@ const app = express(); app.use(compression()); ``` -Per un sito web ad alto traffico in produzione, il modo migliore per mettere in atto la compressione è implementarla a un livello di proxy inverso (vedere [Usa un proxy inverso](#use-a-reverse-proxy)). In tal caso, non è necessario utilizzare middleware di compressione. Per maggiori dettagli sull'attivazione della compressione gzip in Nginx, vedere [Modulo ngx_http_gzip_module](http://nginx.org/en/docs/http/ngx_http_gzip_module) nella documentazione Nginx. +Per un sito web ad alto traffico in produzione, il modo migliore per mettere in atto la compressione è implementarla a un livello di proxy inverso (vedere [Usa un proxy inverso](#use-a-reverse-proxy)). In tal caso, non è necessario utilizzare middleware di compressione. Per maggiori dettagli sull'attivazione della compressione gzip in Nginx, vedere [Modulo ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) nella documentazione Nginx. ### Non utilizzare funzioni sincrone @@ -49,11 +49,11 @@ Le funzioni e i metodi sincroni legano il processo di esecuzione fino al loro ri Sebbene Node e molti moduli forniscano versioni sincrone e asincrone delle loro funzioni, utilizzare sempre la versione asincrona in produzione. L'unico momento in cui una funzione sincrona può essere giustificata è all'avvio iniziale. -Puoi usare il flag da riga di comando `--trace-sync-io` per stampare un avviso e uno stack trace ogni volta che la tua applicazione utilizza un'API sincrona. Naturalmente, non si desidera utilizzare questo in produzione, ma piuttosto per garantire che il codice è pronto per la produzione. Vedi la [documentazione delle opzioni a riga di comando del nodo](https://nodejs.org/api/cli#cli_trace_sync_io) per maggiori informazioni. +Puoi usare il flag da riga di comando `--trace-sync-io` per stampare un avviso e uno stack trace ogni volta che la tua applicazione utilizza un'API sincrona. Naturalmente, non si desidera utilizzare questo in produzione, ma piuttosto per garantire che il codice è pronto per la produzione. Vedi la [documentazione delle opzioni a riga di comando del nodo](https://nodejs.org/api/cli.html#trace-sync-io) per maggiori informazioni. ### Effettuare la registrazione correttamente -In generale, ci sono due motivi per la registrazione dalla tua app: Per il debug e per la registrazione delle attività delle app (essenzialmente, tutto il resto). Usare `console.log()` o `console.error()` per stampare i messaggi di log sul terminale è una pratica comune nello sviluppo. Ma [queste funzioni sono sincrone](https://nodejs.org/api/console#console) quando la destinazione è un terminale o un file, in modo che non siano adatti per la produzione, a meno che non convogliate l'uscita ad un altro programma. +In generale, ci sono due motivi per la registrazione dalla tua app: Per il debug e per la registrazione delle attività delle app (essenzialmente, tutto il resto). Usare `console.log()` o `console.error()` per stampare i messaggi di log sul terminale è una pratica comune nello sviluppo. Ma [queste funzioni sono sincrone](https://nodejs.org/api/console.html) quando la destinazione è un terminale o un file, in modo che non siano adatti per la produzione, a meno che non convogliate l'uscita ad un altro programma. #### Per il debug @@ -134,9 +134,9 @@ La migliore pratica è quella di gestire gli errori il più vicino possibile al Una cosa che dovresti _non_ fare è ascoltare per l'evento `uncaughtException`, emessa quando una bolla di eccezione ritorna fino al ciclo evento. L'aggiunta di un ascoltatore di eventi per `uncaughtException` cambierà il comportamento predefinito del processo che sta incontrando un'eccezione; il processo continuerà a funzionare nonostante l'eccezione. Questo potrebbe sembrare un buon modo per impedire che la tua app si blocchi, ma continuare ad eseguire l'app dopo un'eccezione non catturata è una pratica pericolosa e non è raccomandato, perché lo stato del processo diventa inaffidabile e imprevedibile. -Inoltre, l'utilizzo di `uncaughtException` è ufficialmente riconosciuto come [crude](https://nodejs.org/api/process#process_event_uncaughtexception). Quindi ascoltare `uncaughtException` è solo una cattiva idea. Questo è il motivo per cui consigliamo cose come più processi e supervisori: crash e riavvio è spesso il modo più affidabile per recuperare da un errore. +Inoltre, l'utilizzo di `uncaughtException` è ufficialmente riconosciuto come [crude](https://nodejs.org/api/process.html#event-uncaughtexception). Quindi ascoltare `uncaughtException` è solo una cattiva idea. Questo è il motivo per cui consigliamo cose come più processi e supervisori: crash e riavvio è spesso il modo più affidabile per recuperare da un errore. -Inoltre non consigliamo di utilizzare [domains](https://nodejs.org/api/domain). Generalmente non risolve il problema ed è un modulo deprecato. +Inoltre non consigliamo di utilizzare [domains](https://nodejs.org/api/domain.html). Generalmente non risolve il problema ed è un modulo deprecato. ## Cose da fare nel tuo ambiente / configurazione @@ -240,7 +240,7 @@ Restart=always WantedBy=multi-user.target ``` -Per ulteriori informazioni sul sistema, vedere [systemd reference (man page)](http://www.freedesktop.org/software/systemd/man/systemd.unit). +Per ulteriori informazioni sul sistema, vedere [systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/index.html). ### Esegui la tua app in un cluster @@ -254,7 +254,7 @@ Nelle applicazioni raggruppate, i processi di lavoro possono bloccarsi individua #### Uso del modulo cluster Node -Il cluster è reso possibile con il [modulo cluster di Node](https://nodejs.org/api/cluster). Ciò consente a un processo master di generare processi di lavoro e distribuire le connessioni in entrata tra i lavoratori. +Il cluster è reso possibile con il [modulo cluster di Node](https://nodejs.org/api/cluster.html). Ciò consente a un processo master di generare processi di lavoro e distribuire le connessioni in entrata tra i lavoratori. #### Uso PM2 @@ -294,7 +294,7 @@ Usa un server di cache come [Varnish](https://www.varnish-cache.org/) o [Nginx]( Non importa quanto sia ottimizzata un'app, una singola istanza può gestire solo una quantità limitata di carico e traffico. Un modo per scalare un'app è quello di eseguire più istanze di esso e distribuire il traffico tramite un balancer. La configurazione di un bilanciatore di carico può migliorare le prestazioni e la velocità della tua app e permetterle di scalare più di quanto sia possibile con una singola istanza. -Un bilanciatore di carico è di solito un proxy inverso che orchestra il traffico da e verso più istanze di applicazione e server. Puoi configurare facilmente un bilanciatore di carico per la tua app utilizzando [Nginx](https://nginx.org/en/docs/http/load_balancing) o [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). +Un bilanciatore di carico è di solito un proxy inverso che orchestra il traffico da e verso più istanze di applicazione e server. Puoi configurare facilmente un bilanciatore di carico per la tua app utilizzando [Nginx](https://nginx.org/en/docs/http/load_balancing.html) o [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). Con il bilanciamento del carico, potrebbe essere necessario assicurarsi che le richieste associate a un particolare ID di sessione si connettano al processo che le ha originate. Questo è conosciuto come _session affinity_, o _sticky sessions_, e può essere affrontato dal suggerimento di cui sopra per utilizzare un archivio dati come Redis per i dati di sessione (a seconda della tua applicazione). Per una discussione, vedere [Utilizzo di nodi multipli](https://socket.io/docs/v4/using-multiple-nodes/). diff --git a/src/content/pages/ja/advanced/best-practice-performance.md b/src/content/pages/ja/advanced/best-practice-performance.md index ee1b15f619..a35d429526 100644 --- a/src/content/pages/ja/advanced/best-practice-performance.md +++ b/src/content/pages/ja/advanced/best-practice-performance.md @@ -41,7 +41,7 @@ const app = express(); app.use(compression()); ``` -For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). その場合、圧縮ミドルウェアを使用する必要はありません。 Nginx で gzip 圧縮を有効にする方法については、Nginx ドキュメントの [Module ngx_http_gzip_module](http://nginx.org/en/docs/http/ngx_http_gzip_module) を参照してください。 +For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). その場合、圧縮ミドルウェアを使用する必要はありません。 Nginx で gzip 圧縮を有効にする方法については、Nginx ドキュメントの [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) を参照してください。 ### 同期関数を使用しない @@ -49,11 +49,11 @@ For a high-traffic website in production, the best way to put compression in pla Node と多くのモジュールは同期バージョンと非同期バージョンの関数を提供しますが、本番環境では常に非同期バージョンを使用します。 同期関数を正当化できる唯一の時間は、最初の起動時です。 -`--trace-sync-io` コマンドラインフラグを使用すると、アプリケーションが同期 API を使用するたびに警告とスタックトレースを表示できます。 もちろん、本番環境では使用したくないのではなく、コードが本番環境で使用できるようにしてください。 詳細は [node command-line options documentation](https://nodejs.org/api/cli#cli_trace_sync_io) を参照してください。 +`--trace-sync-io` コマンドラインフラグを使用すると、アプリケーションが同期 API を使用するたびに警告とスタックトレースを表示できます。 もちろん、本番環境では使用したくないのではなく、コードが本番環境で使用できるようにしてください。 詳細は [node command-line options documentation](https://nodejs.org/api/cli.html#trace-sync-io) を参照してください。 ### 正しくログを行う -一般的に、アプリからログを記録するには、次の2つの理由があります。デバッグとアプリアクティビティのロギング(基本的には他のすべて)です。 `console.log()` または `console.error()` を使って、ターミナルにログメッセージを出力するのが一般的です。 デスティネーションが端末やファイルの場合、[これらの関数は同期されます](https://nodejs.org/api/console#console) 別のプログラムに出力を送らない限り生産には向いていません +一般的に、アプリからログを記録するには、次の2つの理由があります。デバッグとアプリアクティビティのロギング(基本的には他のすべて)です。 `console.log()` または `console.error()` を使って、ターミナルにログメッセージを出力するのが一般的です。 デスティネーションが端末やファイルの場合、[これらの関数は同期されます](https://nodejs.org/api/console.html) 別のプログラムに出力を送らない限り生産には向いていません #### デバッグ用 @@ -134,9 +134,9 @@ app.use(async (req, res, next) => { `unchaughtException`をリッスンするのは\_しないでください。 イベントループに戻るまで例外が発生した場合に発生します。 `uncaughtException` に対してイベントリスナーを追加すると、例外に遭遇するプロセスのデフォルトの動作が変更されます。 例外にもかかわらずこのプロセスは続けられます これはアプリがクラッシュするのを防ぐ良い方法に思えるかもしれません。 しかし、未取得の例外が危険な方法であり、推奨されていない場合、アプリを実行し続けます。 プロセスの状態は信頼できず予測不能になるからです -さらに、 `uncaughtException` を使用すると、公式に [crude](https://nodejs.org/api/process#process_event_uncaughtexception) として認識されます。 ですから、 `unchaughtException` を聴くのは悪い考えです。 このため、複数のプロセスやスーパーバイザのようなものをお勧めします。クラッシュと再起動は、多くの場合、エラーから回復する最も信頼性の高い方法です。 +さらに、 `uncaughtException` を使用すると、公式に [crude](https://nodejs.org/api/process.html#event-uncaughtexception) として認識されます。 ですから、 `unchaughtException` を聴くのは悪い考えです。 このため、複数のプロセスやスーパーバイザのようなものをお勧めします。クラッシュと再起動は、多くの場合、エラーから回復する最も信頼性の高い方法です。 -また、 [domains](https://nodejs.org/api/domain) の使用はお勧めしません。 これは一般的に問題を解決せず、非推奨のモジュールです。 +また、 [domains](https://nodejs.org/api/domain.html) の使用はお勧めしません。 これは一般的に問題を解決せず、非推奨のモジュールです。 ## 環境/設定 @@ -240,7 +240,7 @@ Restart=always WantedBy=multi-user.target ``` -systemd の詳細については、[systemd reference (man page)](http://www.freedesktop.org/software/systemd/man/systemd.unit)を参照してください。 +systemd の詳細については、[systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/index.html)を参照してください。 ### クラスターでアプリを実行 @@ -254,7 +254,7 @@ systemd の詳細については、[systemd reference (man page)](http://www.fre #### ノードのクラスタモジュールの使用 -ノードの [cluster module](https://nodejs.org/api/cluster) でクラスタリングが可能になりました。 これにより、マスタープロセスはワーカープロセスを生成し、ワーカー間の受信接続を分配することができます。 +ノードの [cluster module](https://nodejs.org/api/cluster.html) でクラスタリングが可能になりました。 これにより、マスタープロセスはワーカープロセスを生成し、ワーカー間の受信接続を分配することができます。 #### PM2の使用 @@ -294,7 +294,7 @@ For more information on clustering with PM2, see [Cluster Mode](https://pm2.keym どんなに最適化されたアプリであっても、1つのインスタンスは限られた負荷とトラフィックしか処理できません。 アプリを拡張する方法の1つは、アプリの複数のインスタンスを実行し、ロードバランサを介してトラフィックを分散することです。 ロードバランサを設定すると、アプリのパフォーマンスと速度が向上し、1つのインスタンスでより多くのスケールが可能になります。 -ロードバランサは通常、複数のアプリケーションインスタンスとサーバーとの間でトラフィックをオーケストレーションするリバースプロキシです。 アプリのロードバランサーは、 [Nginx](https://nginx.org/en/docs/http/load_balancing) または [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts) を使用して簡単に設定できます。 +ロードバランサは通常、複数のアプリケーションインスタンスとサーバーとの間でトラフィックをオーケストレーションするリバースプロキシです。 アプリのロードバランサーは、 [Nginx](https://nginx.org/en/docs/http/load_balancing.html) または [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts) を使用して簡単に設定できます。 ロードバランシングでは、特定のセッション ID に関連付けられているリクエストがそれらを起動したプロセスに接続されていることを確認する必要があります。 これは*session affinity*または*sticky sessions*として知られています。 そして、セッションデータにRedisなどのデータストアを使用するために上記の提案によって対処される場合があります(アプリケーションによって異なります)。 For a discussion, see [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/). diff --git a/src/content/pages/ko/advanced/best-practice-performance.md b/src/content/pages/ko/advanced/best-practice-performance.md index a98c7fcf6a..22e8498551 100644 --- a/src/content/pages/ko/advanced/best-practice-performance.md +++ b/src/content/pages/ko/advanced/best-practice-performance.md @@ -41,7 +41,7 @@ const app = express(); app.use(compression()); ``` -For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](http://nginx.org/en/docs/http/ngx_http_gzip_module) in the Nginx documentation. +For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation. ### Don't use synchronous functions @@ -49,11 +49,11 @@ Synchronous functions and methods tie up the executing process until they return Although Node and many modules provide synchronous and asynchronous versions of their functions, always use the asynchronous version in production. The only time when a synchronous function can be justified is upon initial startup. -You can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli#cli_trace_sync_io) for more information. +You can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli.html#trace-sync-io) for more information. ### Do logging correctly -In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console#console) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program. +In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console.html) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program. #### For debugging @@ -134,9 +134,9 @@ Best practice is to handle errors as close to the site as possible. So while thi One thing you should _not_ do is to listen for the `uncaughtException` event, emitted when an exception bubbles all the way back to the event loop. Adding an event listener for `uncaughtException` will change the default behavior of the process that is encountering an exception; the process will continue to run despite the exception. This might sound like a good way of preventing your app from crashing, but continuing to run the app after an uncaught exception is a dangerous practice and is not recommended, because the state of the process becomes unreliable and unpredictable. -Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process#process_event_uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error. +Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process.html#event-uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error. -We also don't recommend using [domains](https://nodejs.org/api/domain). It generally doesn't solve the problem and is a deprecated module. +We also don't recommend using [domains](https://nodejs.org/api/domain.html). It generally doesn't solve the problem and is a deprecated module. ## Things to do in your environment / setup @@ -240,7 +240,7 @@ Restart=always WantedBy=multi-user.target ``` -For more information on systemd, see the [systemd reference (man page)](http://www.freedesktop.org/software/systemd/man/systemd.unit). +For more information on systemd, see the [systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/index.html). ### Run your app in a cluster @@ -254,7 +254,7 @@ In clustered apps, worker processes can crash individually without affecting the #### Using Node's cluster module -Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster). This enables a master process to spawn worker processes and distribute incoming connections among the workers. +Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). This enables a master process to spawn worker processes and distribute incoming connections among the workers. #### Using PM2 @@ -294,7 +294,7 @@ Use a caching server like [Varnish](https://www.varnish-cache.org/) or [Nginx](h No matter how optimized an app is, a single instance can handle only a limited amount of load and traffic. One way to scale an app is to run multiple instances of it and distribute the traffic via a load balancer. Setting up a load balancer can improve your app's performance and speed, and enable it to scale more than is possible with a single instance. -A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](https://nginx.org/en/docs/http/load_balancing) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). +A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](https://nginx.org/en/docs/http/load_balancing.html) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). With load balancing, you might have to ensure that requests that are associated with a particular session ID connect to the process that originated them. This is known as _session affinity_, or _sticky sessions_, and may be addressed by the suggestion above to use a data store such as Redis for session data (depending on your application). For a discussion, see [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/). diff --git a/src/content/pages/pt-br/advanced/best-practice-performance.md b/src/content/pages/pt-br/advanced/best-practice-performance.md index cc86d01356..276121caf3 100644 --- a/src/content/pages/pt-br/advanced/best-practice-performance.md +++ b/src/content/pages/pt-br/advanced/best-practice-performance.md @@ -41,7 +41,7 @@ const app = express(); app.use(compression()); ``` -Para um sítio web de alto tráfego, em produção, a melhor maneira de colocar a compressão no lugar é implementá-la a um nível de proxy reverso (veja [usar um proxy reverso](#use-a-reverse-proxy)). Nesse caso, não é necessário utilizar um middleware de compressão. Para detalhes sobre como ativar a compressão gzip no Nginx, consulte [Module ngx_http_gzip_module](http://nginx.org/en/docs/http/ngx_http_gzip_module) na documentação do Nginx. +Para um sítio web de alto tráfego, em produção, a melhor maneira de colocar a compressão no lugar é implementá-la a um nível de proxy reverso (veja [usar um proxy reverso](#use-a-reverse-proxy)). Nesse caso, não é necessário utilizar um middleware de compressão. Para detalhes sobre como ativar a compressão gzip no Nginx, consulte [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) na documentação do Nginx. ### Não usar funções síncronas @@ -49,11 +49,11 @@ Os métodos e funções síncríveis ligam o processo de execução até que ret Embora o Node e muitos módulos fornecem versões sincronizadas e assíncronas de suas funções, sempre use a versão assíncrona em produção. O único momento em que uma função síncrona pode ser justificada é na inicialização inicial. -Você pode usar o sinalizador de linha de comando `--trace-sync-io` para imprimir um aviso e um rastreamento de pilha sempre que seu aplicativo usar uma API síncrona. Claro, você não gostaria de usar isto em produção, mas sim de garantir que seu código esteja pronto para produção. Veja a [documentação de opções de linha de comando do nó](https://nodejs.org/api/cli#cli_trace_sync_io) para mais informações. +Você pode usar o sinalizador de linha de comando `--trace-sync-io` para imprimir um aviso e um rastreamento de pilha sempre que seu aplicativo usar uma API síncrona. Claro, você não gostaria de usar isto em produção, mas sim de garantir que seu código esteja pronto para produção. Veja a [documentação de opções de linha de comando do nó](https://nodejs.org/api/cli.html#trace-sync-io) para mais informações. ### Faça o login corretamente -Em geral, existem duas razões para registrar seu aplicativo: para depuração e para registrar a atividade do aplicativo (essencialmente, tudo o mais). Usar `console.log()` ou `console.error()` para imprimir mensagens de log no terminal é uma prática comum de desenvolvimento. Mas [essas funções são sincronizadas](https://nodejs.org/api/console#console) quando o destino é um terminal ou um arquivo, então eles não são adequados para produção, a menos que você canalize a saída para outro programa. +Em geral, existem duas razões para registrar seu aplicativo: para depuração e para registrar a atividade do aplicativo (essencialmente, tudo o mais). Usar `console.log()` ou `console.error()` para imprimir mensagens de log no terminal é uma prática comum de desenvolvimento. Mas [essas funções são sincronizadas](https://nodejs.org/api/console.html) quando o destino é um terminal ou um arquivo, então eles não são adequados para produção, a menos que você canalize a saída para outro programa. #### Para depuração @@ -134,9 +134,9 @@ A melhor prática é lidar com os erros o mais próximo possível do site. Entã Uma coisa que você não deveria fazer é ouvir o evento `uncaughtException`, emitido quando uma exceção bolha até o laço de repetição do evento. Adicionando um listener de eventos para `uncaughtException` mudará o comportamento padrão do processo que está encontrando uma exceção; o processo continuará a decorrer apesar da excepção. Isso pode soar como uma boa maneira de impedir que seu aplicativo caia, mas continuar a executar o aplicativo após uma exceção não detectada é uma prática perigosa e não é recomendado, porque o estado do processo se torna pouco fiável e imprevisível. -Além disso, usar `uncaughtException` é oficialmente reconhecido como [crude](https://nodejs.org/api/process#process_event_uncaughtexception). Então ouvir por `uncaughtException` é apenas uma má ideia. É por isso que recomendamos coisas como processos múltiplos e supervisores: falhar e reiniciar é muitas vezes a maneira mais confiável de recuperar de um erro. +Além disso, usar `uncaughtException` é oficialmente reconhecido como [crude](https://nodejs.org/api/process.html#event-uncaughtexception). Então ouvir por `uncaughtException` é apenas uma má ideia. É por isso que recomendamos coisas como processos múltiplos e supervisores: falhar e reiniciar é muitas vezes a maneira mais confiável de recuperar de um erro. -Também não recomendamos o uso de [domains](https://nodejs.org/api/domain). Geralmente isso não resolve o problema e é um módulo obsoleto. +Também não recomendamos o uso de [domains](https://nodejs.org/api/domain.html). Geralmente isso não resolve o problema e é um módulo obsoleto. ## Coisas a fazer no seu ambiente / configuração @@ -240,7 +240,7 @@ Restart=always WantedBy=multi-user.target ``` -Para obter mais informações sobre o sistema, consulte a [referência do sistema (man page)](http://www.freedesktop.org/software/systemd/man/systemd.unit). +Para obter mais informações sobre o sistema, consulte a [referência do sistema (man page)](https://www.freedesktop.org/software/systemd/man/latest/index.html). ### Executar seu aplicativo em um cluster @@ -254,7 +254,7 @@ Em apps agrupados, os processos dos trabalhadores podem falhar individualmente s #### Usando módulo de cluster do Node -É possível agrupar com o [módulo cluster do Node](https://nodejs.org/api/cluster). Isto permite a um processo mestre gerar processos de trabalhadores e distribuir conexões de entrada entre os trabalhadores. +É possível agrupar com o [módulo cluster do Node](https://nodejs.org/api/cluster.html). Isto permite a um processo mestre gerar processos de trabalhadores e distribuir conexões de entrada entre os trabalhadores. #### Usando PM2 @@ -294,7 +294,7 @@ Use um servidor de cache como [Varnish](https://www.varnish-cache.org/) ou [Ngin Não importa o quão otimizado um app seja, uma única instância pode manipular apenas uma quantidade limitada de carga e tráfego. Uma maneira de expandir um aplicativo é rodando várias instâncias dele e distribuindo o tráfego através de um balanceador de carga. Configurar um balanceador de carga pode melhorar o desempenho e a velocidade do seu aplicativo, e habilitá-lo a escalar mais do que é possível com uma única instância. -Um balanceador de carga geralmente é um proxy reverso que orqualiza o tráfego de e para a partir de várias instâncias de aplicativos e servidores. Você pode facilmente configurar um balanceador de carga para o seu aplicativo usando [Nginx](https://nginx.org/en/docs/http/load_balancing) ou [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). +Um balanceador de carga geralmente é um proxy reverso que orqualiza o tráfego de e para a partir de várias instâncias de aplicativos e servidores. Você pode facilmente configurar um balanceador de carga para o seu aplicativo usando [Nginx](https://nginx.org/en/docs/http/load_balancing.html) ou [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). Com o balanceamento de carga, você pode ter que garantir que os pedidos que estão associados a um determinado ID de sessão estejam conectados ao processo que os originou. Isto é conhecido como afinidade de sessão, ou _sessões fixas_, e pode ser abordado pela sugestão acima para usar um armazenamento de dados, como Redis para dados de sessão (dependendo do seu aplicativo). Para uma discussão, consulte [Usando múltiplos nós](https://socket.io/docs/v4/using-multiple-nodes/). diff --git a/src/content/pages/zh-cn/advanced/best-practice-performance.md b/src/content/pages/zh-cn/advanced/best-practice-performance.md index a98c7fcf6a..22e8498551 100644 --- a/src/content/pages/zh-cn/advanced/best-practice-performance.md +++ b/src/content/pages/zh-cn/advanced/best-practice-performance.md @@ -41,7 +41,7 @@ const app = express(); app.use(compression()); ``` -For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](http://nginx.org/en/docs/http/ngx_http_gzip_module) in the Nginx documentation. +For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation. ### Don't use synchronous functions @@ -49,11 +49,11 @@ Synchronous functions and methods tie up the executing process until they return Although Node and many modules provide synchronous and asynchronous versions of their functions, always use the asynchronous version in production. The only time when a synchronous function can be justified is upon initial startup. -You can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli#cli_trace_sync_io) for more information. +You can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli.html#trace-sync-io) for more information. ### Do logging correctly -In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console#console) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program. +In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console.html) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program. #### For debugging @@ -134,9 +134,9 @@ Best practice is to handle errors as close to the site as possible. So while thi One thing you should _not_ do is to listen for the `uncaughtException` event, emitted when an exception bubbles all the way back to the event loop. Adding an event listener for `uncaughtException` will change the default behavior of the process that is encountering an exception; the process will continue to run despite the exception. This might sound like a good way of preventing your app from crashing, but continuing to run the app after an uncaught exception is a dangerous practice and is not recommended, because the state of the process becomes unreliable and unpredictable. -Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process#process_event_uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error. +Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process.html#event-uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error. -We also don't recommend using [domains](https://nodejs.org/api/domain). It generally doesn't solve the problem and is a deprecated module. +We also don't recommend using [domains](https://nodejs.org/api/domain.html). It generally doesn't solve the problem and is a deprecated module. ## Things to do in your environment / setup @@ -240,7 +240,7 @@ Restart=always WantedBy=multi-user.target ``` -For more information on systemd, see the [systemd reference (man page)](http://www.freedesktop.org/software/systemd/man/systemd.unit). +For more information on systemd, see the [systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/index.html). ### Run your app in a cluster @@ -254,7 +254,7 @@ In clustered apps, worker processes can crash individually without affecting the #### Using Node's cluster module -Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster). This enables a master process to spawn worker processes and distribute incoming connections among the workers. +Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). This enables a master process to spawn worker processes and distribute incoming connections among the workers. #### Using PM2 @@ -294,7 +294,7 @@ Use a caching server like [Varnish](https://www.varnish-cache.org/) or [Nginx](h No matter how optimized an app is, a single instance can handle only a limited amount of load and traffic. One way to scale an app is to run multiple instances of it and distribute the traffic via a load balancer. Setting up a load balancer can improve your app's performance and speed, and enable it to scale more than is possible with a single instance. -A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](https://nginx.org/en/docs/http/load_balancing) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). +A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](https://nginx.org/en/docs/http/load_balancing.html) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). With load balancing, you might have to ensure that requests that are associated with a particular session ID connect to the process that originated them. This is known as _session affinity_, or _sticky sessions_, and may be addressed by the suggestion above to use a data store such as Redis for session data (depending on your application). For a discussion, see [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/). diff --git a/src/content/pages/zh-tw/advanced/best-practice-performance.md b/src/content/pages/zh-tw/advanced/best-practice-performance.md index a98c7fcf6a..22e8498551 100644 --- a/src/content/pages/zh-tw/advanced/best-practice-performance.md +++ b/src/content/pages/zh-tw/advanced/best-practice-performance.md @@ -41,7 +41,7 @@ const app = express(); app.use(compression()); ``` -For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](http://nginx.org/en/docs/http/ngx_http_gzip_module) in the Nginx documentation. +For a high-traffic website in production, the best way to put compression in place is to implement it at a reverse proxy level (see [Use a reverse proxy](#use-a-reverse-proxy)). In that case, you do not need to use compression middleware. For details on enabling gzip compression in Nginx, see [Module ngx_http_gzip_module](https://nginx.org/en/docs/http/ngx_http_gzip_module.html) in the Nginx documentation. ### Don't use synchronous functions @@ -49,11 +49,11 @@ Synchronous functions and methods tie up the executing process until they return Although Node and many modules provide synchronous and asynchronous versions of their functions, always use the asynchronous version in production. The only time when a synchronous function can be justified is upon initial startup. -You can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli#cli_trace_sync_io) for more information. +You can use the `--trace-sync-io` command-line flag to print a warning and a stack trace whenever your application uses a synchronous API. Of course, you wouldn't want to use this in production, but rather to ensure that your code is ready for production. See the [node command-line options documentation](https://nodejs.org/api/cli.html#trace-sync-io) for more information. ### Do logging correctly -In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console#console) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program. +In general, there are two reasons for logging from your app: For debugging and for logging app activity (essentially, everything else). Using `console.log()` or `console.error()` to print log messages to the terminal is common practice in development. But [these functions are synchronous](https://nodejs.org/api/console.html) when the destination is a terminal or a file, so they are not suitable for production, unless you pipe the output to another program. #### For debugging @@ -134,9 +134,9 @@ Best practice is to handle errors as close to the site as possible. So while thi One thing you should _not_ do is to listen for the `uncaughtException` event, emitted when an exception bubbles all the way back to the event loop. Adding an event listener for `uncaughtException` will change the default behavior of the process that is encountering an exception; the process will continue to run despite the exception. This might sound like a good way of preventing your app from crashing, but continuing to run the app after an uncaught exception is a dangerous practice and is not recommended, because the state of the process becomes unreliable and unpredictable. -Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process#process_event_uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error. +Additionally, using `uncaughtException` is officially recognized as [crude](https://nodejs.org/api/process.html#event-uncaughtexception). So listening for `uncaughtException` is just a bad idea. This is why we recommend things like multiple processes and supervisors: crashing and restarting is often the most reliable way to recover from an error. -We also don't recommend using [domains](https://nodejs.org/api/domain). It generally doesn't solve the problem and is a deprecated module. +We also don't recommend using [domains](https://nodejs.org/api/domain.html). It generally doesn't solve the problem and is a deprecated module. ## Things to do in your environment / setup @@ -240,7 +240,7 @@ Restart=always WantedBy=multi-user.target ``` -For more information on systemd, see the [systemd reference (man page)](http://www.freedesktop.org/software/systemd/man/systemd.unit). +For more information on systemd, see the [systemd reference (man page)](https://www.freedesktop.org/software/systemd/man/latest/index.html). ### Run your app in a cluster @@ -254,7 +254,7 @@ In clustered apps, worker processes can crash individually without affecting the #### Using Node's cluster module -Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster). This enables a master process to spawn worker processes and distribute incoming connections among the workers. +Clustering is made possible with Node's [cluster module](https://nodejs.org/api/cluster.html). This enables a master process to spawn worker processes and distribute incoming connections among the workers. #### Using PM2 @@ -294,7 +294,7 @@ Use a caching server like [Varnish](https://www.varnish-cache.org/) or [Nginx](h No matter how optimized an app is, a single instance can handle only a limited amount of load and traffic. One way to scale an app is to run multiple instances of it and distribute the traffic via a load balancer. Setting up a load balancer can improve your app's performance and speed, and enable it to scale more than is possible with a single instance. -A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](https://nginx.org/en/docs/http/load_balancing) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). +A load balancer is usually a reverse proxy that orchestrates traffic to and from multiple application instances and servers. You can easily set up a load balancer for your app by using [Nginx](https://nginx.org/en/docs/http/load_balancing.html) or [HAProxy](https://www.digitalocean.com/community/tutorials/an-introduction-to-haproxy-and-load-balancing-concepts). With load balancing, you might have to ensure that requests that are associated with a particular session ID connect to the process that originated them. This is known as _session affinity_, or _sticky sessions_, and may be addressed by the suggestion above to use a data store such as Redis for session data (depending on your application). For a discussion, see [Using multiple nodes](https://socket.io/docs/v4/using-multiple-nodes/).