fs模块路径动态拼接
- 动态拼接错误,若提供的操作路径是以./或者…/开头的相对路径时,容易出现拼接错误,因为代码在运行时会以当前执行node命令所处的目录动态拼接出操作文件的完整路径。例如当前处于PS D:\Study\node.js>下输入node命令 ,操作文件的路径是./files/1.txt,那么他会按照D:\Study\node.js\files\1.txt该路径去读取文档。
- 解决办法
出现该问题的原因是给出./
或者../
,要避免这种问题,直接提供完整的文件存放路径例如D:\Study\node.js\1.txt,直接从盘符开始,注意在js中\表示转义字符,因此输入时需要将’\‘替换成’\\',D:\\Study\\node.js\\1.txt。
__dirname表示当前文件所处的目录,因此可以用fs.readFile(__dirname + ‘/files/1.txt’, ‘utf-8’, function(){})
path路径模块
- 路径拼接
path.join()
例如:path.join(‘/a’, ‘/b’, ‘/c’, e); 输出\a\b\c\e
注意../
会抵消前面一层路径,有几个抵消几个 - 获取路径中的文件名
path.basename(path[, ext])
path一个路径字符串
ext可选参数,表示文件扩展名
返回string表示路径中的最后一部分
例如,以下记得导入fs和path模块
const fpath = '/a/b/c/index.html';
var fullName = path.basename(fpath);
console.log(fullName); //输出index.html
var nameWithoutExt = path.basename(fpath, '.html');
console.log(nameWithoutExt); //输出index
- 获取路径中的文件扩展名
path.extname()
例如
const fpath = '/a/b/c/index.html';
const fext = path.extname(fpath);
console.log(fext); //输出 .html
时钟案例
描述:在example.html中存在html代码,css代码,js代码,将他们擦hi分成三个文件,分别是index.html,index.css,index.js.并且将拆分出来的三个文件存放到clock目录中。example.html示例代码在最后
步骤:根据之前学习的知识,考虑使用readFile和writeFile方法读取和写入文件,使用正则表达式将内容划分然后写入各自的文件,注意在写入时,style和script标签记得删除,在html文件中记得加链接。
//首先导入fs模块
const fs = require('fs');
//读取文件内容
fs.readFile('example.html', 'utf-8', function (err, dataStr) {
if (err) {
console.log("文件读取失败!!" + err.message);
return;
}
console.log("文件读取成功!");
// 使用正则表达式匹配CSS代码
const cssRegex = /<style>[\s\S]*<\/style>/;
// 匹配JS代码
const jsRegex = /<script>[\s\S]*<\/script>/;
//对css文件的操作
function resolveCSS(dataStr) {
/*
这行代码使用正则表达式对象cssRegex对字符串dataStr进行匹配。exec()方法会返回一个数组,其中第一个元素是与正则表达式匹配的文本,如果没有匹配到任何内容,则返回null。
*/
const r1 = cssRegex.exec(dataStr);
//将提取出来的字符串做进一步处理,作用是删除掉标签
const newCSS = r1[0].replace('<style>', '').replace('</style>', '');
//将提取出来的css样式写入index.css文件中
fs.writeFile('index.css', newCSS, function (err) {
if (err) {
console.log("css文件写入失败!!" + err.message);
return;
}
console.log("css文件写入成功!");
})
}
//对js文件的操作
function resolveJS(dataStr) {
//使用正则提取页面中的<script></script>标签
const r1 = jsRegex.exec(dataStr);
//将提取出来的字符串做进一步处理
const newCSS = r1[0].replace('<script>', '').replace('</script>', '');
//将提取出来的css样式写入index.js文件中
fs.writeFile('index.js', newCSS, function (err) {
if (err) {
console.log("js文件写入失败!!" + err.message);
return;
}
console.log("js文件写入成功!");
})
}
//对html文件的操作
function resolveHTML(dataStr) {
const newHTML = dataStr.replace(cssRegex, '<link rel="stylesheet" href="index.css"/>').replace(jsRegex, '<script src="index.js"></script>');
//将提取出来的css样式写入index.html文件中
fs.writeFile('index.html', newHTML, function (err) {
if (err) {
console.log("html文件写入失败!!" + err.message);
return;
}
console.log("html文件写入成功!");
})
}
//调用函数
resolveCSS(dataStr);
resolveJS(dataStr);
resolveHTML(dataStr);
})
- 示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<style>
:root {
--light-grey: #f5f6f7;
--dark-blue: #0a0a23;
--fcc-blue: #1b1b32;
--light-yellow: #fecc4c;
--dark-yellow: #feac32;
--light-pink: #ffadad;
--dark-red: #850000;
--light-green: #acd157;
}
body {
font-family: "Lato", Helvetica, Arial, sans-serif;
font-size: 18px;
background-color: var(--fcc-blue);
color: var(--light-grey);
}
h1 {
text-align: center;
}
.container {
width: 90%;
max-width: 680px;
}
h1,
.container,
.output {
margin: 20px auto;
}
label,
legend {
font-weight: bold;
}
.input-container {
display: flex;
flex-direction: column;
}
button {
cursor: pointer;
text-decoration: none;
background-color: var(--light-yellow);
border: 2px solid var(--dark-yellow);
}
button,
input,
select {
min-height: 24px;
color: var(--dark-blue);
}
fieldset,
label,
button,
input,
select {
margin-bottom: 10px;
}
.output {
border: 2px solid var(--light-grey);
padding: 10px;
text-align: center;
}
.hide {
display: none;
}
.output span {
font-weight: bold;
font-size: 1.2em;
}
.surplus {
color: var(--light-pink);
}
.deficit {
color: var(--light-green);
}
</style>
<title>Calorie Counter</title>
</head>
<body>
<main>
<h1>Calorie Counter</h1>
<div class="container">
<form id="calorie-counter">
<label for="budget">Budget</label>
<input type="number" min="0" id="budget" placeholder="Daily calorie budget" required />
<fieldset id="breakfast">
<legend>Breakfast</legend>
<div class="input-container"></div>
</fieldset>
<fieldset id="lunch">
<legend>Lunch</legend>
<div class="input-container"></div>
</fieldset>
<fieldset id="dinner">
<legend>Dinner</legend>
<div class="input-container"></div>
</fieldset>
<fieldset id="snacks">
<legend>Snacks</legend>
<div class="input-container"></div>
</fieldset>
<fieldset id="exercise">
<legend>Exercise</legend>
<div class="input-container"></div>
</fieldset>
<div class="controls">
<span>
<label for="entry-dropdown">Add food or exercise:</label>
<select id="entry-dropdown" name="options">
<option value="breakfast" selected>Breakfast</option>
<option value="lunch">Lunch</option>
<option value="dinner">Dinner</option>
<option value="snacks">Snacks</option>
<option value="exercise">Exercise</option>
</select>
<button type="button" id="add-entry">Add Entry</button>
</span>
</div>
<div>
<button type="submit">
Calculate Remaining Calories
</button>
<button type="button" id="clear">Clear</button>
</div>
</form>
<div id="output" class="output hide"></div>
</div>
</main>
<script>
const calorieCounter = document.getElementById('calorie-counter');
const budgetNumberInput = document.getElementById('budget');
const entryDropdown = document.getElementById('entry-dropdown');
const addEntryButton = document.getElementById('add-entry');
const clearButton = document.getElementById('clear');
const output = document.getElementById('output');
let isError = false;
function cleanInputString(str) {
const regex = /[+-\s]/g;
return str.replace(regex, '');
}
function isInvalidInput(str) {
const regex = /\d+e\d+/i;
return str.match(regex);
}
function addEntry() {
const targetInputContainer = document.querySelector(`#${entryDropdown.value} .input-container`);
const entryNumber = targetInputContainer.querySelectorAll('input[type="text"]').length + 1;
const HTMLString = `
<label for="${entryDropdown.value}-${entryNumber}-name">Entry ${entryNumber} Name</label>
<input type="text" id="${entryDropdown.value}-${entryNumber}-name" placeholder="Name" />
<label for="${entryDropdown.value}-${entryNumber}-calories">Entry ${entryNumber} Calories</label>
<input
type="number"
min="0"
id="${entryDropdown.value}-${entryNumber}-calories"
placeholder="Calories"
/>`;
targetInputContainer.insertAdjacentHTML('beforeend', HTMLString);
}
function calculateCalories(e) {
e.preventDefault();
isError = false;
const breakfastNumberInputs = document.querySelectorAll('#breakfast input[type=number]');
const lunchNumberInputs = document.querySelectorAll('#lunch input[type=number]');
const dinnerNumberInputs = document.querySelectorAll('#dinner input[type=number]');
const snacksNumberInputs = document.querySelectorAll('#snacks input[type=number]');
const exerciseNumberInputs = document.querySelectorAll('#exercise input[type=number]');
const breakfastCalories = getCaloriesFromInputs(breakfastNumberInputs);
const lunchCalories = getCaloriesFromInputs(lunchNumberInputs);
const dinnerCalories = getCaloriesFromInputs(dinnerNumberInputs);
const snacksCalories = getCaloriesFromInputs(snacksNumberInputs);
const exerciseCalories = getCaloriesFromInputs(exerciseNumberInputs);
const budgetCalories = getCaloriesFromInputs([budgetNumberInput]);
if (isError) {
return;
}
const consumedCalories = breakfastCalories + lunchCalories + dinnerCalories + snacksCalories;
const remainingCalories = budgetCalories - consumedCalories + exerciseCalories;
const surplusOrDeficit = remainingCalories < 0 ? 'Surplus' : 'Deficit';
output.innerHTML = `
<span class="${surplusOrDeficit.toLowerCase()}">${Math.abs(remainingCalories)} Calorie ${surplusOrDeficit}</span>
<hr>
<p>${budgetCalories} Calories Budgeted</p>
<p>${consumedCalories} Calories Consumed</p>
<p>${exerciseCalories} Calories Burned</p>
`;
output.classList.remove('hide');
}
function getCaloriesFromInputs(list) {
let calories = 0;
for (const item of list) {
const currVal = cleanInputString(item.value);
const invalidInputMatch = isInvalidInput(currVal);
if (invalidInputMatch) {
alert(`Invalid Input: ${invalidInputMatch[0]}`);
isError = true;
return null;
}
calories += Number(currVal);
}
return calories;
}
function clearForm() {
const inputContainers = Array.from(document.querySelectorAll('.input-container'));
for (const container of inputContainers) {
container.innerHTML = '';
}
budgetNumberInput.value = '';
output.innerText = '';
output.classList.add('hide');
}
addEntryButton.addEventListener("click", addEntry);
calorieCounter.addEventListener("submit", calculateCalories);
clearButton.addEventListener('click', clearForm);
</script>
</body>
</html>