Skip to content

Commit be9a27d

Browse files
AbigailDengAbigailDeng
authored andcommitted
feat: readFileSync
1 parent 20d821d commit be9a27d

File tree

2 files changed

+31
-6
lines changed

2 files changed

+31
-6
lines changed

src/index.js

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,15 +10,31 @@ import check from 'check-node-version';
1010
import { execSync } from 'child_process';
1111
import commands from './command/index.js';
1212
import RC from './rc/index.js';
13-
import { createRequire } from 'module'; // Bring in the ability to create the 'require' method
14-
const require = createRequire(import.meta.url); // construct the require method
15-
const pkg = require('../package.json');
13+
import { readFileSync } from 'fs';
14+
import { fileURLToPath } from 'url';
15+
import path from 'path';
1616
import { logger } from './utils/myLogger.js';
1717
import { userHomeDir } from './utils/userHomeDir.js';
1818

1919
const minVersion = '10.9.0';
2020

21+
export function getPackageJson() {
22+
let dirname;
23+
try {
24+
// for test as we cannot use import.meta.url in Jest
25+
dirname = __dirname;
26+
} catch {
27+
const __filename = fileURLToPath(import.meta.url);
28+
dirname = path.dirname(__filename);
29+
}
30+
const filePath = path.resolve(dirname, '../package.json');
31+
const data = readFileSync(filePath, 'utf-8');
32+
const packageJson = JSON.parse(data);
33+
return packageJson;
34+
}
35+
2136
function init(options) {
37+
const pkg = getPackageJson();
2238
const commander = new Command();
2339
// Configuration for test
2440
if (options?.exitOverride) {

test/index.test.js

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,7 @@ import path from 'path';
33
import check from 'check-node-version';
44
import updateNotifier from 'update-notifier';
55
import { logger } from '../src/utils/myLogger.js';
6-
import { createRequire } from 'module'; // Bring in the ability to create the 'require' method
7-
const require = createRequire(import.meta.url); // construct the require method
8-
const pkg = require('../package.json');
6+
import { getPackageJson } from '../src/index.js';
97

108
const commandBin = path.resolve(__dirname, '../bin/aelf-command.js');
119

@@ -17,7 +15,18 @@ jest.mock('child_process', () => {
1715
};
1816
});
1917
jest.mock('../src/utils/myLogger.js');
18+
19+
describe('test get packagon json', () => {
20+
test('should return correct packagon json', () => {
21+
const pkg = getPackageJson();
22+
expect(pkg.name).toBe('aelf-command');
23+
});
24+
});
2025
describe('test index', () => {
26+
let pkg;
27+
beforeEach(() => {
28+
pkg = getPackageJson();
29+
});
2130
afterEach(() => {
2231
// Restore any mocks
2332
jest.restoreAllMocks();

0 commit comments

Comments
 (0)