Node.js概述

108 阅读1分钟

Node.js简介

Node.js 就是一个运行在服务器环境的 Javascript,是一个异步的非阻塞的基于事件驱动的运行时。

Node.js 基于 Google 的 V8 引擎。

所有 Node.js 都可以编写成一个 JS 文件

如何运行 Node.js

我们先来创建一个 helloworld.js

//helloworld.js
console.log("hello world")

然后在命令行输入:

node helloworld.js

就可以获得以下结果:

hellow.png

常用内置模块

  • path:获取路径

  • fs:读文件

  • http/httpsNode.js 网络的关键模块,允许 Node.js 通过 HTTP 传输数据

  • until:提供常用函数的集合

接下来简单介绍两种常用模块,其他未提及的模块可以参考Node.js官方说明文档

path模块

path 模块的作用是获取路径

首先来创建一个 path.js

// demo.js
const path = require('path')
// 通过require加载nodejs内置的path模块拿到path对象

const myPath = '/path.js'

// 对象path上挂在的方法dirname、basename、extname
const dirname = path.dirname(myPath)
// dirname 拿到path对应目录
const basename = path.basename(myPath)
// basename 拿到path对应文件名
const extname = path.extname(myPath)
// extname 拿到path文件对应扩展名

console.log(dirname)
console.log(basename)
console.log(extname)

在命令行输入

node .\path.js

就可以得到以下结果:

GT[ILK5%D7J}IIB]JL@B$Y5.png

http模块

http 模块的作用是允许 Node.js 通过 HTTP 传输数据

首先来创建一个 js 文件 http.js

// http.js
const http = require('http')
// 使用 require 加载 http 模块

const hostname = '127.0.0.1'
// 定义地址
const port = 3000
// 定义端口

// 使用 createServer 方法创建一个 server 服务
const server = http.createServer((req, res) => {
  res.statusCode = 200
  res.setHeader('Content-Type', 'text/plain')
  res.end('Hello, World!\n')
})

// server 有一个 listen 方法去监听端口 3000
server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`)
})

在命令行输入

node .\http.js

就可以得到以下结果:

http.png

总结

Node.js 就是运行在服务器的 Javascript,它包含许多内置的模块,我们可以使用 require 来引入这些模块。