nodeJs 学习
常用快捷键
二、fs模块
回调函数为空,则表示写入成功!
练习
const fs = require('fs');
fs.readFile('../files/成绩.txt', 'utf-8', (err, dataStr) => {
if (err) {
console.log('读取失败');
return err;
}
console.log('读取成功');
const arr = dataStr.split(' ')
const newArr = arr.map(item => item.replace('=', ':'));
fs.writeFile('../files/02.txt', newArr.join('\r\n'), (err) => {
if (err) {
console.log('写入失败');
return;
}
console.log('写入成功');
})
})
fs模块,路径动态拼接,与执行的时候路径有关;
const fs = require('fs')
fs.readFile('D:\\ty\\code\\nodeJs\\nodeDemo01\\files\\02.txt', 'utf-8', (err,data) => {
console.log(1,err,data)
})
fs.readFile(__dirname+'../../files/02.txt', 'utf-8', (err,data) => {
console.log(2,err,data)
})
path模块
获取路径中的文件名
获取路径中的文件扩展名
案例
完整代码:
const fs = require('fs');
const path = require('path');
const regStyle = /<style>[\s\S]*<\/style>/;
const regScript = /<script>[\s\S]*<\/script>/;
fs.readFile(path.join(__dirname, '../files/ty.html'), 'utf-8', (err, data) => {
if (err) {
return;
}
console.log(data)
resolveCss(data)
resolveJs(data)
resolveHtml(data);
})
function resolveCss (htmlStr) {
const r1 = regStyle.exec(htmlStr);
// console.log(r1)
const newCss = r1[0].replace('<style>', '').replace('</style>', '');
// console.log(newCss)
fs.writeFile(path.join(__dirname, './clock/index.css'), newCss, err => {
console.log(err)
})
}
function resolveJs (htmlStr) {
const r1 = regScript.exec(htmlStr);
console.log(r1)
const newJs = r1[0].replace('<script>', '').replace('</script>', '');
console.log(newJs)
fs.writeFile(path.join(__dirname, './clock/index.js'), newJs, err => {
console.log(err)
})
}
function resolveHtml (htmlStr) {
const newHtml = htmlStr
.replace(regStyle, '<link rel="stylesheet",href="./css"></link>')
.replace(regScript, '<script src="./index.js"></script>');
fs.writeFile(path.join(__dirname, '/clock/index.html'), newHtml, err => {
console.log(err)
})
}
三http模块
const http = require('http');
const server = http.createServer();
server.on('request', function(req, res) {
console.log('请求了')
})
server.listen(8080, () => {
console.log('服务器已启动:http://127.0.0.1:8080')
})