【若川视野 x 源码共读】第27期 | read-pkg

59 阅读1分钟

作用:解析package.json

用法

import {readPackage} from 'read-pkg';

console.log(await readPackage());
//=> {name: 'read-pkg', …}

console.log(await readPackage({cwd: 'some-other-directory'}));
//=> {name: 'unicorn', …}

源码

import process from 'node:process';
//node 文件系统
import fs, {promises as fsPromises} from 'node:fs';
import path from 'node:path';
//fileURLToPath 将文件URL解码为路径字符串
import {fileURLToPath} from 'node:url';
//解析json
import parseJson from 'parse-json';
//规范化它从 package.json 文件中读取的数据
import normalizePackageData from 'normalize-package-data';

const toPath = urlOrPath => urlOrPath instanceof URL ? fileURLToPath(urlOrPath) : urlOrPath;

export async function readPackage({cwd, normalize = true} = {}) {
	cwd = toPath(cwd) || process.cwd();  //process.cwd() 返回运行当前脚本的工作目录的路径
	const filePath = path.resolve(cwd, 'package.json');  //得到package.json路径
  //同步读文件并解析
	const json = parseJson(await fsPromises.readFile(filePath, 'utf8'));

  //标准化读取的package.json数据
	if (normalize) {
		normalizePackageData(json);
	}

	return json;
}

export function readPackageSync({cwd, normalize = true} = {}) {
	cwd = toPath(cwd) || process.cwd();
	const filePath = path.resolve(cwd, 'package.json');
  //异步读文件
	const json = parseJson(fs.readFileSync(filePath, 'utf8'));

	if (normalize) {
		normalizePackageData(json);
	}

	return json;
}
Footer
© 2022 GitHub, Inc.
Footer navigation
Ter