window学习node中的一些快捷键:
1、输入文件名时,tab=键可自动补全;
2、esc快捷键可清空当前命令;
3、输入cls可清屏;
fs模块
const fs = require('fs')
// 参数(path [,option], callback)
fs.readFile('./filePath', 'utf8', function(err, dataStr) {
// 如果文件读取成功,则err为null;如果文件读取失败,则err为错误对象,dataStr为undefined
console.log(err)
console.log(dataStr)
})
// write只能用来创建文件,不能创建路径
fs.writeFile('./filePath2', 'abcd', function(err) {
// 如果文件写入成功,则err为null;如果文件写入失败,则err为错误对象,
// \r\n换行
console.log(err)
})
注意:在使用fs模块时,如果提供的操作路径是以./或…/开头的相对路径时,很容易出现路径拼接错误。会以执行node命令时所处的目录,动态拼接出被操作文件的完整路径。
解决方法:
第一种、提供操作文件的完整存放路径,从盘符开始(C:\ \…)
第二种、__dirname表示当前文件所处的目录
path模块
const path = require('path')
// join拼接路径
const pathStr = path.join('/a', '/b/c', '../', './d', 'e')
console.log(pathStr) // 输出\a\b\d\e
const fpath = '/a/b/c/index.html'
// basename可以从一个路径中获取文件的名称部分
const fullName = path.basename(fpath)
console.log(fullName) // 输出index.html
const fullName = path.basename(fpath, html)
console.log(fullName) // 输出index
// extname获取扩展名部分
const fext = path.extname(fpath)
console.log(fext) // 输出.html
http模块
服务器和普通电脑的区别在于,服务器上安装了web服务器软件,例如:IIS、Apache等。通过安装这些服务器软件,就能把一台普通的电脑变成一台Web服务器。
在node.js中,我们不需要使用IIS、Apache等这些第三方web服务器软件。因为我们可以基于node.js提供的http模块,轻松手写一个服务器软件,从而对外提供web服务。
// 1、导入http模块
const http = require('http')
// 2、创建web服务器实例
const server = http.createServer()
// 3、为服务器实例绑定request事件
server.on('request', (req, res) => {
// req中存放客户端相关的数据或属性
const url = req.url
const method = req.method
const str = `your url is ${url}, and request method is ${method}`
// res存放服务端相关的数据或属性
console.log('有客户端来请求我们的服务器~')
// 设置响应头,解决乱码问题
res.setHeader('Content-Type', 'text/html; charset=utf-8')
// 调用res.end向客户端发送指定的内容,并结束这次请求的处理过程
res.end(str)
})
// 4、启动服务器
server.listen(80, () => {
console.log('服务器运行在http://127.0.0.1:80')
})