Sometimes, there are Node.js scripts that you may want to run on a regular basis without any interaction. Perhaps you want to ping a server every half-hour or download new data regularly from a news API. Whatever your use case, being able to automate those scripts would save you time and effort.

If you’re working on a Mac, a great way of automating these scripts is using launchd to set an automated schedule. It can run asynchronous code, will run your tasks when the Mac wakes up, and most importantly, it’s already a part of macOS, meaning there’s no need to install new tools!

Let’s look at what it takes to get started with launchd and Node.js.


What Is launchd?

“launchd manages processes, both for the system as a whole and for individual users.” — Terminal launchd man page

launchd is a tool for running daemons and agents on macOS. If you aren’t familiar with these terms, a daemon is a system-wide service that is always running in the background, while agents are services that are executed on user-specific requests. As such, launchd is the preferred macOS automation tool for running scripts.

In this tutorial, we will be making user-specific requests to run a Node.js script, so we will make use of launch agents. These agents allow a user to define a task by using a property list (.plist) file that can be executed on a regular schedule as set by the user. launchd can automate tasks both periodically (using a set interval between executions) and on a calendar-based schedule, allowing for flexibility in the way you schedule your scripts to run.


Automating Node.js Scripts

Now that we know the basics of what launchd is, let’s put together a simple Node.js script to test it with. We’ll first set the agent to run it every minute, then change it to execute on a calendar-based schedule to demonstrate both ways we can define automated tasks.

Create a test script

To begin, we will create a new folder on our desktop and place an empty JavaScript file inside:

mkdir ~/Desktop/schedule-demo && touch ~/Desktop/schedule-demo/schedule.js

Note: Technically, this file can be called whatever you like and stored wherever you like as long as you update the path to the code in the remaining instructions.

Now that we have a file to use, let’s put a simple console.log timestamp inside by pasting the following into our new file:

const now = new Date();

const currentTime = `${now.getHours()}:${now.getMinutes()}`;
console.log(`The time is ${currentTime}`);

This console.log will output the current time when the script is run. We can test this script using Node and check whether we are getting a correct output in our Terminal:

#javascript #macos #programming #nodejs #automation

Schedule Node.js Scripts on Your Mac With Launchd
4.95 GEEK