Setting up a Node.js web server on a Raspberry Pi: A step-by-step guide
A few years back, I acquired a Raspberry Pi Model B , and recently decided to transform it into a web server. This journey highlighted a key point: a Raspberry Pi functions as a miniature PC, requiring an operating system (OS). This contrasts with boards like Arduino, which execute programs directly without an OS.
Here’s how to build a Node.js web server on a Raspberry Pi from scratch:
This tool facilitates installing Raspberry Pi OS onto a microSD card. While alternatives like Debian or Ubuntu exist, Raspberry Pi OS is officially recommended for optimal performance.
Launch Raspberry Pi Imager and configure these settings:
I used the default settings. Upon completion, you'll see a success message:
Note the microSD card's location.
After booting, you'll see the desktop welcome screen:
Your Raspberry Pi OS is now ready.
Open a terminal and run these commands:
<code class="language-bash">sudo apt-get update -y sudo apt-get dist-upgrade -y</code>
<code class="language-bash">sudo apt-get install nodejs -y sudo apt-get install npm -y</code>
Verify installation:
<code class="language-bash">node -v npm -v</code>
Express simplifies web server creation. I used the generator with default options:
<code class="language-bash">sudo apt-get update -y sudo apt-get dist-upgrade -y</code>
<code class="language-bash">sudo apt-get install nodejs -y sudo apt-get install npm -y</code>
<code class="language-bash">node -v npm -v</code>
The server defaults to port 3000. Access it from another device using the Raspberry Pi's IP address (e.g., http://192.168.1.239:3000
).
Your Express app is now network-accessible. Note that older models like the B might have slower processing times due to limited resources.
Conclusion:
The Raspberry Pi's versatility extends to IoT integration. While the B has limitations, newer models offer enhanced performance. The ability to run a Linux OS unlocks a wide range of package installations.
Extra:
Initially, I attempted Next.js, encountering a "JavaScript heap out of memory" error. Express proved a more suitable alternative for this older board. Remember resource constraints when choosing frameworks.
The above is the detailed content of How to Set Up a Node.js Web Server on Raspberry Pi. For more information, please follow other related articles on the PHP Chinese website!