The Raspberry Pi single board computers are highly useful and there are countless fun projects for them, including switching appliances on and off using GPIO, LED light shows for Christmas, file servers for your home network, among numerous other things.
Combine that with Linux, and you have a world of functionality at your fingertips. If you’re using Raspbian or DietPi, it is Debian-based and the following instructions to run a program on startup should work, however I have only tested them on the DietPi operating system (on the PI 3 B+) so far.
To run a program on startup or when your Raspberry Pi reboots, you can use the ‘crontab’ command. Crontab is a task scheduling utility found on many Linux operating systems and is highly useful. The first step is to identify what you want to run. Is it a bash script or binary? If so, just type the following to open an editor where you’ll place the path to the command you’re running:
crontab -e
You should see the following come up in a text editor. Scroll to the bottom and add the line highlighted in green, in which ‘fileserver’ is a fake example program/script you might want to run on startup (useful in the event of a power failure so you don’t have to keep turning on your monitor and starting the server manually):
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h dom mon dow command
@reboot /home/username/fileserver
Unfortunately, if you were to try this with something like a Node.js command, it may not work. For example: ‘nodejs app.js’ won’t necessarily work. If you find a workaround, please let me know in the comments!