Cập nhật ngày 17/11/2021
Chuẩn bị
- Chắc chắc bạn đã cài NodeJs rồi nhé
Bước 1.
Upload source của bạn lên Hosting (public_html hay htdocs gì đó…)
Bước 2. Mở cổng cho NodeJs
Cổng thì các bạn tự mở, ví dụ ở đây mình dùng cổng 5000
- index.js
var http = require("http"); http.createServer(function (request, response) { // Send the HTTP header // HTTP Status: 200 : OK // Content Type: text/plain response.writeHead(200, {'Content-Type': 'text/plain'}); // Send the response body as "Hello World" response.end('Hello World\n'); }).listen(5000); // Console will print the message console.log('Server running!/');
Bước 3. Chạy NodeJs
Vào SSH
node index.js
Bước 4. Chạy NodeJs mà không cần SSH (Tùy chọn)
Cài forever và nodemon để server tiếp tục chạy kể cả khi tắt SSH console và tự khởi động lại khi code có thay đổi.
npm install forever nodemon -g
Chạy index.js
forever start --minUptime 1000 --spinSleepTime 1000 --killSignal=SIGTERM -c "nodemon --exitcrash" index.js
Mà có cái này cũng làm được
node app.js &