What advantages does using `prestart` offer compared to `&&` in a command within `package.json`?

I believe the title speaks for itself, but let's dive in:

What advantages does using the pre-script of npm package.json, like prestart, have over simply combining commands with && in the start script?

{
  prestart: "parcel build",
  start "nodemon server.js"
}

compared to

{
 start: "parcel build && nodemon server.js" 
}

Is it more suitable for different platforms?
Can it handle running two asynchronous endless processes, such as two servers (build + api)?

Any other benefits?

Edit: I found a benefit for postInstall. Platforms like Heroku remove devDependency after running npm install, so in the postinstall I can execute the build process before Heroku removes the necessary code.

Answer №1

prestart executes prior to start as the name suggests, leading to a sequential execution of commands in both steps rather than running them in parallel. When using && in start, the commands are executed sequentially but within the same step.

Both approaches yield similar results, but there could be compatibility concerns with && on specific Windows versions.

To perform parallel command execution, you can utilize & within start instead of &&.

Answer №2

Aside from what has already been mentioned, it is important to highlight that the prestart hook in the package.json file is not compatible with the yarn package manager. Therefore, utilizing && offers a smoother transition between npm and yarn (assuming your shell can interpret &&).

This decision was made to enhance maintainability by steering clear of implicit dependency chains:

We deliberately refrain from supporting arbitrary pre and post hooks for user-defined scripts (like prestart). This practice, inherited from npm, resulted in scripts being implicit rather than explicit, making the execution flow unclear. It also led to unexpected outcomes, such as running both yarn serve and yarn preserve. https://yarnpkg.com/advanced/lifecycle-scripts

Answer №3

These techniques are primarily used to enhance code readability and facilitate the separation of logical processes.

In terms of compatibility, npm typically executes all scripts within the local shell environment. This means that on most Linux systems, it will utilize a sh clone, while on Windows it will use cmd. There may be instances where certain shell functionalities like && are not supported. However, it's rare and usually unnecessary to cater to such edge cases, especially since users can easily install bash on any platform where Node.js is present and configure npm accordingly. Personally, I prefer using bash in npm scripts for consistency and document this choice in the README file.

If you need to manage multiple long-running processes, tools like pm2 (https://github.com/Unitech/PM2/) are recommended for production environments. During development, running processes in separate terminals to monitor logs is helpful – consider using supervisor (https://github.com/petruisfan/node-supervisor) to automatically restart processes upon errors or modifications.

Furthermore, creating .sh scripts for maintenance tasks such as deployment and periodic operations is common practice. These scripts can be executed via npm by defining them as named scripts within the scripts section of your project.

Answer №4

The reason for this is that when you execute a script such as npm install && npm start, both commands are run within the same process in node. Therefore, if one of the commands returns a non-zero exit code (such as an exception), it becomes difficult to pinpoint which command actually failed. By running them as separate scripts using the "pre" keyword, they are executed in separate processes, providing more accurate results.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the purpose of storing JSON data as a string within another JSON object?

Screenshot of developer tools While exploring the local storage on my visit to YouTube, I came across some very peculiar-looking JSON data. { creation: 1638112285935, data: "{\"quality\":1080,\"previousQuality&bs ...

Exploring the possibilities of launching a worldwide npm module using the harmony flag

I have developed an npm module called dm-npm that can be globally installed. I enjoy using the co library in this module. Is there a way to inform the module to run with the harmony flag when launched globally? Below is the content of the package.json f ...

The difference between using document.getElementsByTagName("img") and document.getElementById('testimg')

My HTML code is as follows: <a href="index.php"><img id="testimg" src="images/logo.png"/></a> This is my JavaScript code: function getW(){ var theImg = document.getElementById('testimg'); return theImg; } theImg = ...

Unable to find the required dependency: peer tslint@ "^5.0.0 || ^6.0.0" in [email protected] node_modules/codelyzer development codelyzer@ "^5.1.2" from the main project directory

Struggling to create my angular project, I've attempted updating @angular/core and even deleted the node modules folder and reinstalled it. I also played around with the version of my node and npm, but nothing seems to work. Here's the error: [1 ...

Converting rotation into a directional vector

I have a Three.js object and I am able to read its rotation. However, I am looking for a way to extract a vec3 that indicates the direction in which the object is currently rotated. Can someone provide guidance on how to achieve this? ...

Save Bson query as a Javascript log

When working with Java to create a complex MongoDB query, I often log the query before executing it: log.info("Filter: {}", queryFilter); The logged query output typically looks like this: And Filter{filters=[Filter{fieldName='FinInstrmGnlAttrbts.C ...

Show or hide the sibling element of the current element without using a specific identifier in jQuery

I am looking to make div.edit-button toggle its corresponding sibling div.additionalFieldForm. There are multiple instances of both on the page, so I want to target only the pair that are related within the same group. If a div.edit-button is clicked, the ...

How to incorporate template literals when sending JSON responses in Node.js?

Utilizing express and aiming to return some JSON, I am considering using a template literal. Here is my current approach: resp.status(201).json({ message: "Customer added to database", url: "http://localhost:5000/Customer/" + doc._id ...

Transfer the html div element to the ajax request

My server-side code runs multiple bigquery queries and organizes the results in a table. The client calls this code via an ajax request. I want to send the table/div generated by the server-side code to the client so that it can be rendered there. Is this ...

Tips for placing order import styles css module as the first line in eslint-plugin-import configuration

I'm currently setting up ESLint for my project, using `eslint-plugin-import` to organize module import order. However, I have a specific case with a style CSS module that I want to place at the beginning of the import list. How can I configure ESLint ...

I am facing an issue with TypeScript as it is preventing me from passing the prop in React and Zustand

interface ArticuloCompra { id: string; cantidad: number; titulo: string; precio: number; descuento: number; descripcion: string; imagen: string; } const enviarComprasUsuarios = ({ grupos, }: { grupos: { [key: string]: ArticuloCompra & ...

What is the best way to limit input to only numbers and special characters?

Here is the code snippet I am working with: <input style="text-align: right;font-size: 12px;" class='input' (keyup.enter)="sumTotal($event)" type="text" [ngModel]="field.value" (focusin)="focusin()" (focusout)="format()" (keyup.ente ...

Using Vue.js, you can set a method to return data directly to

Having just begun my journey with Vue, I find myself in a bit of a predicament. As part of my learning process, I am developing an app for tracking episodes in TV series. The initial step involves searching for series and adding them to a database. When co ...

Rearrange the position of the customized google map marker to appear just above the latitude

Can you provide guidance on how to move a customized Google Map marker above a specific latitude and longitude point? You can view the code structure in this JSBIN: Link. I have used three object arrays for reference. Where should I insert the "anchor" i ...

Issue encountered while trying to determine the Angular version due to errors in the development packages

My ng command is displaying the following version details: Angular CLI: 10.2.0 Node: 12.16.3 OS: win32 x64 Angular: <error> ... animations, cdk, common, compiler, compiler-cli, core, forms ... language-service, material, platform-browser ... platfor ...

The dynamic form is programmed to display identical values for both the initial and subsequent inputs

Currently, I am developing a personalized dynamic form utilizing the Material UI library as the component for my React Js application. You can find more information about this library at https://mui.com/. In front of you is the initial setup of the dynami ...

Exploring Angular's Dependency Injection

How can I verify that a module has properly loaded its required dependencies? I've added ngAnimate to the module definition, but it doesn't appear to be functioning within the application when it runs. The environment I'm navigating is quite ...

Having trouble with Node.js child_process.exec when the command doesn't return any output?

Recently encountered an issue while using child_process.exec in nodejs. The problem occurs when the command returns nothing. Here is what I did: const {exec} = require('child_process'); const cmd = `ps -ef | grep -v grep | grep abc123.py`; exec ...

Tips for moving an input bar aside to make room for another

Is it feasible to have two input bars next to each other and keep one open until the other is clicked, then the first one closes as well? I attempted using a transition with "autofocus," but the bar ends up closing when clicked on in my site. If anyone ca ...

JavaScript: Dynamically load a script when a particular <a> element is in an active state

<script> function DisplayTag(){ var q1=document.getElementById( 'ctl00_ContentPlaceHolder1_ctl00_ctl00_Showcase' ).childNodes[1].innerHTML; var counter1=0; function executeScript(q1,counter1){ q1= document.getElementById( 'ctl00_Co ...