使用js获取文件内容
wǎng luò shí huāng 2023-12-29
工具
getFileContent
在浏览器客户端读取 json 文件内容
# 使用 js 不是 nodejs 获取文件内容
方法一:获取指定路径下的 json 文件内容
// getFileContent.ts
import fs from "fs";
import chalk from "chalk"; // https://www.npmjs.com/package/chalk
/** 输出日志 */
const chalkWrapper = (chalkFunc, arg) => (typeof arg === "string" ? chalkFunc(arg) : arg);
export const logger = {
log: (...args) => {
console.log(chalk.blue("[log]"), ...args.map((arg) => chalkWrapper(chalk.blue, arg)));
},
error: (...args) => {
console.log(chalk.red("[error]"), ...args.map((arg) => chalkWrapper(chalk.red, arg)));
},
info: (...args) => {
console.log(chalk.green("[info]"), ...args.map((arg) => chalkWrapper(chalk.green, arg)));
},
};
/** 进程优雅自杀 */
export const gracefulSuicide = (msg, err) => {
console.log(chalk.red("\n================= [build error] =================\n"));
console.log(chalk.red(msg));
if (err) {
console.error(err);
}
console.log(chalk.red("\n================= [build error] =================\n"));
process.exit(1);
};
/** 获取文件,文件不存在则报错退出 */
export const getFileBufferOrDie = (fileDest) => {
try {
const content = fs.readFileSync(fileDest);
return content;
} catch (error) {
gracefulSuicide(`'${fileDest}' doesn't exsist, please make sure you've done 'npm run build' !`, error);
}
};
/** 获取 JSON,格式不合法则报错退出 */
export const getJsonOrDie = (fileDest) => {
try {
const jsonObjBuffer = getFileBufferOrDie(fileDest);
const jsonObj = JSON.parse(jsonObjBuffer.toString());
return jsonObj;
} catch (error) {
gracefulSuicide(`File ${fileDest} isn't a valid JSON, please make sure you've configured it right !`, error);
}
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
例如我们直接获取 .json 文件的内容:
import { getJsonOrDie } from './getFileContent.ts'
const { appKey, version } = getJsonOrDie('package.json') // 这里就可以拿到json文件里关键字对应的值
1
2
3
2
3
方法二:直接获取 json 文件的内容
function readJsonContent(jsonFile) {
return new Promise((resolve, reject) => {
var reader = new FileReader(); //这里是核心!!!读取操作就是由它完成的。
reader.onload = function (event) {
let json = JSON.parse(event.target.result);
resolve(json);
};
reader.onerror = function (event) {
reject("获取失败!");
};
reader.readAsText(jsonFile); //读取文件的内容
});
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
2
3
4
5
6
7
8
9
10
11
12
13
14
15