From be9a27d9698a4a10882ca37cf2a62554e555f408 Mon Sep 17 00:00:00 2001 From: AbigailDeng Date: Tue, 30 Jul 2024 13:06:44 +0800 Subject: [PATCH] feat: readFileSync --- src/index.js | 22 +++++++++++++++++++--- test/index.test.js | 15 ++++++++++++--- 2 files changed, 31 insertions(+), 6 deletions(-) diff --git a/src/index.js b/src/index.js index e6e583e..ccc1528 100644 --- a/src/index.js +++ b/src/index.js @@ -10,15 +10,31 @@ import check from 'check-node-version'; import { execSync } from 'child_process'; import commands from './command/index.js'; import RC from './rc/index.js'; -import { createRequire } from 'module'; // Bring in the ability to create the 'require' method -const require = createRequire(import.meta.url); // construct the require method -const pkg = require('../package.json'); +import { readFileSync } from 'fs'; +import { fileURLToPath } from 'url'; +import path from 'path'; import { logger } from './utils/myLogger.js'; import { userHomeDir } from './utils/userHomeDir.js'; const minVersion = '10.9.0'; +export function getPackageJson() { + let dirname; + try { + // for test as we cannot use import.meta.url in Jest + dirname = __dirname; + } catch { + const __filename = fileURLToPath(import.meta.url); + dirname = path.dirname(__filename); + } + const filePath = path.resolve(dirname, '../package.json'); + const data = readFileSync(filePath, 'utf-8'); + const packageJson = JSON.parse(data); + return packageJson; +} + function init(options) { + const pkg = getPackageJson(); const commander = new Command(); // Configuration for test if (options?.exitOverride) { diff --git a/test/index.test.js b/test/index.test.js index af711c4..d503b35 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -3,9 +3,7 @@ import path from 'path'; import check from 'check-node-version'; import updateNotifier from 'update-notifier'; import { logger } from '../src/utils/myLogger.js'; -import { createRequire } from 'module'; // Bring in the ability to create the 'require' method -const require = createRequire(import.meta.url); // construct the require method -const pkg = require('../package.json'); +import { getPackageJson } from '../src/index.js'; const commandBin = path.resolve(__dirname, '../bin/aelf-command.js'); @@ -17,7 +15,18 @@ jest.mock('child_process', () => { }; }); jest.mock('../src/utils/myLogger.js'); + +describe('test get packagon json', () => { + test('should return correct packagon json', () => { + const pkg = getPackageJson(); + expect(pkg.name).toBe('aelf-command'); + }); +}); describe('test index', () => { + let pkg; + beforeEach(() => { + pkg = getPackageJson(); + }); afterEach(() => { // Restore any mocks jest.restoreAllMocks();