4midori
4midori

Reputation: 486

Output to command line within npm scripts?

I have a script in my package.json with the following code:

"scripts": {
    "build": "postcss tailwind/tailwind.css -o css/cenic.tailwind.css",
    "watch": "postcss tailwind/tailwind.css -o css/cenic.tailwind.css --watch"
}

It works fine. but how do I get it to output text to the command line, something like

script ran at {{ date(now) }}

In other words, I want to see a notification when a script has run.

Upvotes: 13

Views: 10871

Answers (1)

RobC
RobC

Reputation: 24952

Cross Platform (Windows/Linux/macOS...)

You can do the following to log the date/time when the script begins its task:

"build": "node -e \"console.log('script started at: %s', Date())\" && postcss tailwind/tailwind.css -o css/cenic.tailwind.css"

Explanation:

  1. The part on the left side of the && operator that reads;

    node -e \"console.log('script started at: %s', Date())\"
    
    • utilizes Node.js command line option -e to evaluate the inline JavaScript.
    • The inline script utilizes JavaScript's console.log(...) and Date().
  2. The commands on the right side of the && operator are whatever command(s) you want to run, in your scenario it's the postcss command.

Variations:

  • To color the log you could add some ANSI/VT100 Control sequences. For instance:

    "build": "node -e \"console.log('%sscript started at: %s%s', '\\x1b[42;30m', Date(), '\\x1b[0m' )\" && postcss tailwind/tailwind.css -o css/cenic.tailwind.css"
    
  • To log when the npm script completed instead of started you can switch the order of the commands. For example:

    "build": "postcss tailwind/tailwind.css -o css/cenic.tailwind.css && node -e \"console.log('script completed at: %s', Date())\""
    

Nix platforms only (Linux/MacOS...)

If you only want a solution that runs on *nix platforms, then you can do the following instead:

"build": "echo \"script started at: $(date)\" && postcss tailwind/tailwind.css -o css/cenic.tailwind.css"

Explanation:

  1. The part on the left side of the && operator that reads:

    echo \"script started at: $(date)\"
    
    • utilizes the shells echo command to print the message to the command line.
    • Command substitution, i.e. the $(...) part, is utilized to obtain the output from the shells date command.
  2. The commands on the right side of the && operator are whatever command(s) you want to run, in your scenario it's the postcss command.

If you want to apply visual styling to the echo command please refer to my answer here

Upvotes: 18

Related Questions