How to use node.js built-in modules fs, path, http

NodeJs is divided into two parts

One is for the V8 engine to parse and execute JS code.

The second is the built-in API, so that JS can call these APIs to complete some back-end operations.
Built-in API modules (fs, path, http, etc.)
third-party API modules (express, mysql, etc.)

fs module

The fs.readFile() method is used to read the contents of the specified file.
The fs.writeFile() method is used to write content to the executed file

// fs 文件读写模块
fs.readFile(path[, options], callback)

// path:必选,字符串,表示文件路径。
// options:可选,表示以什么编码格式来读取文件。
// callback:必选,文件读取完成后,通过回调函数拿到读取的结果。
fs.readFile('./file.txt', 'utf8', function(err, sucess){
    
    
	// 打印失败的结果
	// 读取失败时err会返回错误对象,sucess会返回undefined
	console.log(err)
	console.log("-------------------------")
	// 打印成功的结果
	console.log(sucess)
})
const fs = require("fs")
// 2.调用fs.writeFile()方法,写入文件内容
// 	参数1:读取文件的存放路径
// 	参数2:data:表示要写入的内容。
// 	参数3:表示以什么格式写入文件内容,默认值是utf8。
// 	参数4:文件写入完成后的回调函数。
fs.writeFile('./file.txt', "Holle", 'utf8', function(err){
    
    
	// 打印失败的结果
	console.log(err)
})

path path processing module

path.join() method, used to splice multiple path fragments into a complete path string

The path.basename() method is used to parse the file name from the path string

 // 合成路径的时候,'…/'会抵消掉一层路径

const path = require('path')

const path = path.join('/a', '/b/c', '../', './d', 'e')
console.log(path)
// \a\b\d\e
const path2 = path.join(__dirname, './files/123.txt')
console.log(path2)
// __dirname:表示当前js文件所处的目录
// path.basename(),从一个文件路径中,获取到文件的名称部分:

const path = require('path')

const path = '/a/b/c/index.html'
var fullName = path.basename(path)
console.log(fullName)
// index.html

var n = path.basename(path, ".html" )
console.log(n)
// index

// 使用path.extname()方法,可以获取路径中的扩展名部分

const path = require('path')

const fpath = '/a/b/c/index.html'
const fext = path.extname(fpath)
console.log(fext)
// .html

http

Through the http.createServer() method provided by the http module, an ordinary computer can be turned into a web server to provide web resource services to the outside world.

/ 导入http模块
const http = require('http')
// 创建web 服务器实例
const server = http.createServer()
// 为服务器实例绑定request事件,监听客户端的请求
server.on( 'request', (req,res) => {
    
    
// req 客户端请求信息
// res 服务器响应信息

// 解决中文乱码问题
//发送的内容包含中文
	const str =`您请求的url地址是${
      
      req.url},请求的 method类型是${
      
      req.method}`
	// 为了防止中文显示乱码的问题,需要设置响应头Content-Type 的值为 text/html; charset=utf-8
	res.setHeader( 'Content-Type',  'text/html; charset=utf-8')
	// 把包含中文的内容,响应给客户端
    res.end(str)

	// 只要有客户端来请求我们自己的服务器,就会触发request 事件,从而调用这个事件处理函数
    console.log( 'Someone visit our web server.' )
})

// 启动服务器
server.listen(8080, () =>{
    
    
	console.log('http server running at http://127.0.0.1:8080')
})

只要有人访问http://127.0.0.1:8080,那么终端就会打印Someone visit our web server.但是由于没有写任何返回值,页面会等着客户端返回数据。

Guess you like

Origin blog.csdn.net/Xiang_Gong_Ya_/article/details/132312731