Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Changing the npm start-script of Node.js
The start-script of a Node.js application consists of all the commands that will be used to perform specific tasks. When starting or initializing a Node.js project, there are predefined scripts that will be created for running the application. These scripts can be changed as per the need or demand of the project.
Script commands are widely used for making different startup scripts of programs in both Node and React. npm start is used for executing a startup script without typing its execution command.
Package.json File Structure
The start script needs to be added in the package.json file. The name of the file here is 'index.js', but you can change this name as per your needs.
"scripts": {
"start": "node index.js" // Name of the file
}
Below is an illustration showing the implementation of startup script:
Example - Basic Express Server
Create a file named index.js and copy the below code snippet. After creating the file, use the command npm start to run this code as shown in the example below:
// Importing the express module
const express = require('express');
const app = express();
// Initializing the data with the following string
var data = "Welcome to TutorialsPoint !";
// Sending the response for '/' path
app.get('/', (req, res) => {
// Sending the data json text
res.send(data);
});
// Setting up the server at port 3000
app.listen(3000, () => {
console.log("server running");
});
Running the Application
To run the application, use the following command in your terminal:
C:\home\node>> npm start
The above statement will run the index.js file. This command starts the main class for the project and you should see the output:
server running
Now hit the following URL from your browser to access the webpage: http://localhost:3000
Custom Start Scripts
You can customize your start script to include additional options or run different files:
"scripts": {
"start": "node server.js",
"dev": "nodemon index.js",
"start:prod": "NODE_ENV=production node index.js"
}
Conclusion
The npm start script provides a convenient way to run Node.js applications. By customizing the scripts section in package.json, you can define different startup commands for various environments and development needs.
