1.什么是node.js?
2.知道node.js可以做什么?
3.能够说出Node.js中JS的组成部分?
4.能够使用fs读写文件操作?
5.能够使用path模块处理路径?
6.能够使用http模块写一个基本的web服务器?
javaScript能否做后端开发?
readFile(path, options, callback)
PS: 若文件读取成功err为null
const fs = require("fs");
fs.readFile("sample.txt", "utf-8", function(err, dataStr) {
if (err) {
console.log(err);
}
else console.log(dataStr);
});
writeFile(path, data, options, callback)
fs.writeFile("sample.txt", "123abc", "utf-8", function (err) {
if (err) {
console.log(err);
} else console.log("文件写入成功。");
});
const fs = require("fs");
// 1.读取文件
fs.readFile("studentsScore.txt", "utf-8", function (err, data) {
if (err) {
console.log("文件读取失败!\r\n", err);
} else {
// 2.使用split()将读取后的文件以空格进行拆分,返回数组对象
const oldData = data.split(" ");
// 3.创建一个新数组,用于存储学生成绩格式化后的数据
const arrNew = [];
// 3.1 使用forEach()遍历数组每个对象
oldData.forEach((item) => {
// 3.2 使用replace()将'='替换成':'
arrNew.push(item.replace("=", ":"));
});
// 4. 使用join()将arrNew数组成员通过换行符拼接起来
const newStr = arrNew.join("\r\n");
// 5. 使用writeFile()写入文件
fs.writeFile("studentsScore-OK.txt", newStr, "utf-8", function (err) {
if (err) {
console.log("文件写入失败!", err);
} else console.log("文件写入成功!");
});
}
});
const fs = require("fs");
const path = require("path");
// 正则匹配CSS样式部分
const regStyle = /", "");
fs.writeFile(
path.join(__dirname, "/files/clock/index.css"),
content,
"utf-8",
function (err) {
if (err) {
console.log("写入文件失败!", err.message);
return;
} else {
console.log("写入css文件成功!");
return;
}
}
);
}
// 定义提取js代码函数
function scriptResolve(htmlStr) {
const scriptRes = regJs.exec(htmlStr);
const content = scriptRes[0].replace("", "");
fs.writeFile(
path.join(__dirname, "/files/clock/index.js"),
content,
"utf-8",
function (err) {
console.log(err ? `写入文件失败!${err.message}` : `写入js文件成功!`);
}
);
}
// 定义提取html代码函数
function htmlResolve(htmlStr) {
const htmlRes = htmlStr
.replace(regStyle, '')
.replace(regJs, '');
fs.writeFile(
path.join(__dirname, "/files/clock/index.html"),
htmlRes,
"utf-8",
function (err) {
console.log(err ? `写入文件失败!${err.message}` : `写入html文件成功!`);
}
);
}
PS: