Home > Article > Web Front-end > nodejs steps
Node.js is an open source, cross-platform JavaScript runtime environment that can use JavaScript to write back-end servers. This article will introduce the installation and usage steps of Node.js.
Go to the Node.js official website to download the installation program suitable for your operating system. The installer will install the Node.js operating environment for your system. and npm (Node Package Manager). npm is the package manager for Node.js, used to install and manage Node.js modules.
Use command line tools to create a new project folder in any location. In the folder, run the following command to create the package.json file of the Node.js project:
npm init
This command will ask you some questions about the project, such as project name, version, author, etc.
Install the required modules via npm as follows:
npm install <module-name> --save
This will be in the current folder Create a node_modules folder and install the given module. In addition, the --save
parameter will add this module to the project's package.json file, so that npm will automatically install and configure this module when the project is installed on other devices.
Create the main file of the project, usually with .js
as the extension. You can use any text editor to create the file like Notepad, Sublime, Atom, etc.
In the newly created main file, write the Node.js code. For example, write a simple HTTP server:
const http = require('http'); const hostname = '127.0.0.1'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World '); }); server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
This is a very simple Node.js HTTP server that listens on local port 3000 and responds to all incoming requests. The code imports the HTTP module through require('http')
to handle HTTP requests and responses.
Use the command line tool, enter the project folder, and execute the following command to run the newly written Node.js code:
node <filename>.js
This will start the Node.js server and start listening on the port you specified in the code.
Visit http://localhost:3000
in your browser, you will see the "Hello World" message.
Summary
These are the basic steps for using Node.js. You can write complex server applications and tools by learning, practicing, and using Node.js. Thank you for reading this article and happy studying!
The above is the detailed content of nodejs steps. For more information, please follow other related articles on the PHP Chinese website!