官术网_书友最值得收藏!

Installing and running Node.js

To install Node.js, visit https://nodejs.org, and download and run the installer package for the currently recommended version. The examples in this book are based on Node.js v6, released in April 2016 and supported through to April 2018.

After installation, open up a console window (run command prompt on Windows, or terminal on Mac) and type node.

This opens the Node.js REPL, which works like the JavaScript console in browsers. Try typing in a few commands and see the output:

> function square(x) { return x*x; }
undefined
> square(42)
1764
> new Date()
2016-05-02T16:08:41.915Z
> var foo = { bar: 'baz' }
undefined
> typeof foo
'object'
> foo.bar
'baz'

Now let's make use of one of the Node.js-specific APIs to create an HTTP server. Type the following commands into the REPL (the output of each command is omitted from the listing below for brevity):

> var listener = function(request, response) { response.end('Hello World!') }
> require('http').createServer(listener).listen(3000)

Now try visiting http://localhost:3000 in your browser. Congratulations! You have written your first web server, in just two lines of code. The first line defines a callback function for handling HTTP requests and returning a response. The second line sets up a new server that accepts HTTP requests on port 3000 and invokes our callback function for each request.

You can exit the Node.js REPL by typing process.exit().

主站蜘蛛池模板: 商洛市| 洛宁县| 辉南县| 东平县| 广饶县| 新野县| 永福县| 黄石市| 六安市| 柳林县| 手机| 若尔盖县| 汝城县| 鞍山市| 张掖市| 涡阳县| 安宁市| 出国| 韶山市| 岫岩| 镇平县| 特克斯县| 靖安县| 永胜县| 岚皋县| 综艺| 图片| 克拉玛依市| 青岛市| 刚察县| 宜州市| 托克托县| 重庆市| 新绛县| 定南县| 穆棱市| 开原市| 交口县| 黔南| 牙克石市| 库尔勒市|