Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การเปลี่ยน npm start-script ใน Node.js

Start-script ของโปรเจกต์ Node.js ประกอบด้วยคำสั่งสำหรับรันแอปพลิเคชัน เมื่อเริ่มโปรเจกต์ใหม่ จะมีสคริปต์เริ่มต้นสร้างขึ้นมา สามารถปรับเปลี่ยนได้ตามความต้องการ คำสั่ง npm start ใช้รันสคริปต์ startup โดยไม่ต้องพิมพ์คำสั่งรันเต็มๆ

ไฟล์ package.json

เพิ่มสคริปต์ start ใน package.json (สมมติไฟล์หลักชื่อ index.js):

"scripts": {
  "start": "node index.js"
}

ตัวอย่าง: แอป Express พื้นฐาน

สร้าง index.js แล้วรันด้วย npm start

index.js

const express = require('express');
const app = express();

var data = "Welcome to TutorialsPoint !";

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

app.listen(3000, () => {
  console.log("server running");
});

การทดสอบ

  1. รัน npm start
  2. เปิดเบราว์เซอร์ไปที่ https://localhost:3000
  3. จะเห็นข้อความ "Welcome to TutorialsPoint !"

รูปภาพตัวอย่าง UI ถูกละเว้น