- Node.js Web Development
- David Herron
- 271字
- 2021-06-25 21:54:02
Launching a server with Node.js
Many scripts that you'll run are server processes. We'll be running lots of these scripts later on. Since we're still in the dual mode of verifying the installation and familiarizing you with using Node.js, we want to run a simple HTTP server. Let's borrow the simple server script on the Node.js home page (http://nodejs.org).
Create a file named app.js containing the following:
const http = require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/plain'}); res.end('Hello, World!\n'); }).listen(8124, '127.0.0.1'); console.log('Server running at http://127.0.0.1:8124');
Run it as follows:
$ node app.js Server running at http://127.0.0.1:8124
This is the simplest of web servers you can build with Node.js. If you're interested in how it works, flip forward to Chapter 4, HTTP Servers and Clients; Chapter 5, Your First Express Application; and Chapter 6, Implementing the Mobile-First Paradigm. For the moment, just visit http://127.0.0.1:8124 in your browser to see the Hello, World! message:
A question to ponder is why this script did not exit when ls.js did exit. In both cases, execution of the script reaches the end of the script; the Node.js process does not exit in app.js, while in ls.js it does.
The reason is the presence of active event listeners. Node.js always starts up an event loop, and in app.js, the listen function creates an event listener that implements the HTTP protocol. This event listener keeps app.js running until you do something such as typing Ctrl + C in the Terminal window. In ls.js, there is nothing that creates a long-running event listener, so when ls.js reaches the end of its script, the node process will exit.
- ASP.NET Core:Cloud-ready,Enterprise Web Application Development
- Python概率統(tǒng)計(jì)
- Learn TypeScript 3 by Building Web Applications
- 自然語言處理實(shí)戰(zhàn):預(yù)訓(xùn)練模型應(yīng)用及其產(chǎn)品化
- iOS 9 Game Development Essentials
- Python爬蟲開發(fā):從入門到實(shí)戰(zhàn)(微課版)
- 區(qū)塊鏈架構(gòu)與實(shí)現(xiàn):Cosmos詳解
- JMeter 性能測(cè)試實(shí)戰(zhàn)(第2版)
- JavaScript 網(wǎng)頁編程從入門到精通 (清華社"視頻大講堂"大系·網(wǎng)絡(luò)開發(fā)視頻大講堂)
- Vue.js快速入門與深入實(shí)戰(zhàn)
- R語言數(shù)據(jù)可視化之美:專業(yè)圖表繪制指南
- Kotlin Standard Library Cookbook
- STM32F0實(shí)戰(zhàn):基于HAL庫開發(fā)
- 大數(shù)據(jù)分析與應(yīng)用實(shí)戰(zhàn):統(tǒng)計(jì)機(jī)器學(xué)習(xí)之?dāng)?shù)據(jù)導(dǎo)向編程
- Java高并發(fā)核心編程(卷1):NIO、Netty、Redis、ZooKeeper