DEV Community

Cover image for Writing Shell Commands for Node.js via SSH
payam1382
payam1382

Posted on

Writing Shell Commands for Node.js via SSH

Writing Shell Commands for Node.js via SSH

Introduction

Using SSH (Secure Shell) to manage Node.js applications on remote servers allows developers to efficiently control their projects. This article explores essential commands and techniques for working with Node.js via an SSH environment.

Connecting via SSH

To start, you need to connect to your remote server using an SSH client. On Windows, you might use PuTTY, while macOS and Linux users can use the Terminal. The command is typically:

ssh username@your-server-ip
Enter fullscreen mode Exit fullscreen mode

Replace username and your-server-ip with your credentials.

Checking Node.js Installation

Once connected, verify if Node.js is installed:

node -v
Enter fullscreen mode Exit fullscreen mode

This command displays the installed version. If Node.js isn’t installed, you can install it via a package manager like apt or yum, depending on your server's OS.

Setting Up a Node.js Project

To create a new Node.js application, follow these steps:

  1. Create a new directory:
   mkdir myapp
Enter fullscreen mode Exit fullscreen mode
  1. Navigate into the directory:
   cd myapp
Enter fullscreen mode Exit fullscreen mode
  1. Initialize a new Node.js project:
   npm init -y
Enter fullscreen mode Exit fullscreen mode

This command generates a package.json file with default settings.

Installing Packages

To add dependencies, use the npm install command:

npm install express
Enter fullscreen mode Exit fullscreen mode

This example installs the Express framework. You can delve into other packages as needed.

Creating and Running Your Application

Next, create your main JavaScript file:

touch app.js
Enter fullscreen mode Exit fullscreen mode

Open app.js in a text editor (like nano or vim) and add your application code. For instance:

const express = require('express');
const app = express();
const PORT = process.env.PORT || 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
});

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});
Enter fullscreen mode Exit fullscreen mode

To run your application, use:

node app.js
Enter fullscreen mode Exit fullscreen mode

Managing Processes

For production environments, consider using a process manager like pm2:

npm install -g pm2
pm2 start app.js
Enter fullscreen mode Exit fullscreen mode

This allows your app to run in the background and restart automatically if it crashes.

Conclusion

Using SSH to manage Node.js applications provides the ultimate control and flexibility for developers. By mastering basic shell commands and setups, you can efficiently develop and deploy your projects on remote servers.
دوربین سیمکارتی-دوربین کوچک-دوربین مداربسته-مالکد

Top comments (0)