UNPKG

1.31 kBJavaScriptView Raw
1const path = require('path');
2const fs = require('fs');
3const message = require('../utils/message');
4
5/**
6 * @description 这样获取 package.json 可以防止 require 缓存
7 * @param {String} cwd 当前目录
8 * @returns {Object} pkgJSON content
9 */
10function getPkgJSON(cwd) {
11 const pkgJSONPath = path.join(cwd, './package.json');
12 return getJSON(pkgJSONPath);
13}
14
15/**
16 * @description 这样获取 package.json 可以防止 require 缓存
17 * @param {String} jsonPath 当前目录
18 * @returns {Object} json content
19 */
20function getJSON(jsonPath) {
21 if (!fs.existsSync(jsonPath)) {
22 throw new Error(message.invalid);
23 }
24 const jsonString = fs.readFileSync(jsonPath, 'utf-8');
25 return JSON.parse(jsonString);
26}
27
28/**
29 * 写package.json
30 * @param {Object} pkg
31 * @param {String} cwd
32 */
33function writePkgJSON(pkg, cwd) {
34 const pkgJSONPath = path.join(cwd, './package.json');
35 writeJSON(pkg, pkgJSONPath);
36}
37
38/**
39 * 写json
40 * @param {Object} obj jsonObject
41 * @param {String} jsonPath jsonFilePath
42 */
43function writeJSON(obj, jsonPath) {
44 if (!fs.existsSync(jsonPath)) {
45 throw new Error(message.invalid);
46 }
47 const jsonString = JSON.stringify(obj, null, 2);
48 fs.writeFileSync(jsonPath, jsonString, 'utf-8');
49}
50
51module.exports = {
52 getPkgJSON,
53 writePkgJSON,
54 getJSON,
55 writeJSON,
56};