Browse Source

Node.js day2:文件读写

daxia 2 năm trước cách đây
mục cha
commit
37ccdf4b5d

+ 26 - 0
19_Node.js/day-2/code/index.html

@@ -0,0 +1,26 @@
+<!DOCTYPE html>
+<html lang="en">
+  <head>
+    <meta charset="UTF-8" />
+    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+    <title>Document</title>
+  </head>
+  <body>
+    <script>
+      var p;
+      try {
+        p = new Promise((res, rej) => {
+          // 抛出异常后 会将promise对象 变成失败的状态
+          throw new Error('就是这么傲娇.');
+          rej('莫名其妙 无理取闹'); // 将promise对象 变成失败的状态
+        });
+        // .catch((err) => err);
+      } catch (error) {
+        console.error('走了吗', error);
+      }
+
+      console.log(p);
+    </script>
+  </body>
+</html>

+ 9 - 0
19_Node.js/day-2/code/index.js

@@ -0,0 +1,9 @@
+// fs
+// import { writeFileAsync } from './learn:fs.mjs';
+// writeFileAsync();
+
+// import { appendFileAsync } from './learn:fs.mjs';
+// appendFileAsync('\n不知道写点啥了');
+
+import { readFileAsync } from './learn:fs.mjs';
+readFileAsync();

+ 40 - 0
19_Node.js/day-2/code/learn:fs.mjs

@@ -0,0 +1,40 @@
+import { writeFile, appendFile, readFile } from 'node:fs/promises';
+
+/**
+ *! writeFile 写
+ */
+export async function writeFileAsync() {
+  try {
+    await writeFile('./log.txt', 'heheda');
+    console.log('写入成功');
+  } catch (error) {
+    console.error('写入失败:', error);
+  }
+}
+
+/**
+ *! appendFile 向文件末尾追加内容
+ */
+
+export async function appendFileAsync(data = '') {
+  try {
+    await appendFile('./log.append.txt', data);
+    console.log('写入成功');
+  } catch (error) {
+    console.error('写入失败:', error);
+  }
+}
+
+/**
+ *! readFile 读取文件内容
+ */
+
+export async function readFileAsync() {
+  try {
+    // 默认读取的内容 是 二进制数据的16进制编码 数据
+    // let content = await readFile('./log.append.txt');
+    let content = await readFile('./log.append.txt', 'utf8');
+
+    console.log(content);
+  } catch (error) {}
+}

+ 2 - 0
19_Node.js/day-2/code/log.append.txt

@@ -0,0 +1,2 @@
+heiheihaheiheiha
+不知道写点啥了

+ 1 - 0
19_Node.js/day-2/code/log.txt

@@ -0,0 +1 @@
+heheda

+ 13 - 0
19_Node.js/day-2/code/package.json

@@ -0,0 +1,13 @@
+{
+  "name": "code",
+  "version": "1.0.0",
+  "description": "",
+  "main": "index.js",
+  "type": "module",
+  "scripts": {
+    "test": "echo \"Error: no test specified\" && exit 1"
+  },
+  "keywords": [],
+  "author": "",
+  "license": "ISC"
+}