Welcome to our comprehensive guide on Running Node.js Scripts! This tutorial is designed to help beginners and intermediates understand and master the art of running Node.js scripts.
Node.js is an open-source, cross-platform, JavaScript runtime environment that allows you to run JavaScript on the server-side and build scalable and high-performance applications.
To start running Node.js scripts, you'll first need to install Node.js on your computer. You can download it from the official Node.js website: Node.js Downloads
Let's create a simple Node.js script that prints "Hello, World!" to the console.
// Save this as helloWorld.js
console.log('Hello, World!');To run this script, open your terminal (Command Prompt on Windows, Terminal on Mac/Linux), navigate to the directory containing the script, and execute the following command:
node helloWorld.jsš Your "Hello, World!" should now appear in the terminal! š
A typical Node.js application consists of multiple files and directories organized in a specific structure. Let's discuss some important ones:
package.json: A manifest file that contains vital information about the project, such as its name, version, and dependencies.node_modules: A folder that contains all the libraries and packages your project depends on.scripts: A key in the package.json file that defines custom scripts for your project.Node Package Manager (NPM) allows you to run custom scripts within your project. To create an NPM script, update the scripts key in your package.json file:
{
"name": "my-app",
"version": "1.0.0",
"scripts": {
"start": "node app.js"
}
}Now you can run the script by executing the following command:
npm startTo run scripts using external modules, you'll first need to install them using NPM. For example, to install the popular Express.js web framework, run:
npm install expressNow, let's create a simple Express.js server that listens for requests on port 3000:
// Save this as app.js
const express = require('express');
const app = express();
const port = 3000;
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});To run this server, execute the following command:
node app.jsVisit http://localhost:3000 in your web browser to see the output! š
What command do you use to run a Node.js script from the terminal?
This tutorial covered the basics of running Node.js scripts, including creating and running scripts, understanding the Node.js file structure, and using NPM scripts. In the following lessons, we'll dive deeper into Node.js by exploring modules, the Express.js web framework, and more. Happy coding! š