Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: Migrate the whole project from cjs to esm #137

Merged
merged 20 commits into from
Sep 24, 2024
16 changes: 8 additions & 8 deletions bin/fanyi.js → bin/fanyi.mjs
100755 → 100644
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
#!/usr/bin/env -S node --no-deprecation

const { Command } = require('commander');
const chalk = require('chalk');
const updateNotifier = require('update-notifier');
const pkg = require('../package.json');
const config = require('../lib/config');
const { searchList } = require('../lib/searchHistory');
import { Command } from 'commander';
import chalk from 'chalk';
import updateNotifier from 'update-notifier';
import pkg from '../package.json';
import config from '../lib/config.mjs';
import { searchList } from '../lib/searchHistory.mjs';

updateNotifier({ pkg }).notify();
const program = new Command();
Expand Down Expand Up @@ -82,6 +82,6 @@ if (!process.argv.slice(2).length) {
async function runFY(options = {}) {
const defaultOptions = await config.load();
const mergedOptions = { ...defaultOptions, ...options };
const fanyi = require('..');
fanyi(program.args.join(' '), mergedOptions);
const fanyi = await import('..');
fanyi.default(program.args.join(' '), mergedOptions);
}
14 changes: 7 additions & 7 deletions index.js → index.mjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const { Groq } = require('groq-sdk');
const print = require('./lib/print');
const fetch = (...args) => import('node-fetch').then(({ default: fetch }) => fetch(...args));
const { XMLParser } = require('fast-xml-parser');
const ora = require('ora');
const gradient = require('gradient-string');
import { Groq } from 'groq-sdk';
import print from './lib/print.mjs';
import { XMLParser } from 'fast-xml-parser';
import ora from 'ora';
import gradient from 'gradient-string';
import fetch from 'node-fetch';

const gradients = [
'cristal',
Expand All @@ -21,7 +21,7 @@ const gradients = [
'rainbow',
];

module.exports = async (word, options) => {
export default async (word, options) => {
console.log('');
const { iciba, groq, GROQ_API_KEY } = options;
const endcodedWord = encodeURIComponent(word);
Expand Down
19 changes: 10 additions & 9 deletions lib/config.js → lib/config.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
const homedir = process.env.HOME || require('node:os').homedir();
const path = require('node:path');
const fs = require('node:fs');
const chalk = require('chalk');
import { homedir } from 'node:os';
import path from 'node:path';
import { existsSync, statSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
import chalk from 'chalk';

const configDir = path.resolve(homedir, '.config', 'fanyi');
const configPath = path.resolve(configDir, '.fanyirc');

Expand All @@ -11,8 +12,8 @@ const chalkInstance = new chalk.Instance({ level: 3 });
const config = {
async load(path = configPath) {
const emptyObj = {};
if (fs.existsSync(path) && fs.statSync(path).isFile()) {
const content = fs.readFileSync(path, 'utf-8');
if (existsSync(path) && statSync(path).isFile()) {
const content = readFileSync(path, 'utf-8');
try {
return JSON.parse(content.toString());
} catch (e) {
Expand All @@ -26,8 +27,8 @@ const config = {
const defaultOptions = await config.load(path);
const mergedOptions = { ...defaultOptions, ...options };
const content = JSON.stringify(mergedOptions, null, 2);
fs.existsSync(configDir) || fs.mkdirSync(configDir, { recursive: true });
fs.writeFileSync(path, content);
existsSync(configDir) || mkdirSync(configDir, { recursive: true });
writeFileSync(path, content);
console.log(
`${chalkInstance.bgGreen(JSON.stringify(options))} config saved at ${chalkInstance.gray(path)}:`,
);
Expand All @@ -40,4 +41,4 @@ const config = {
},
};

module.exports = config;
export default config;
6 changes: 3 additions & 3 deletions lib/print.js → lib/print.mjs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const { saveHistory } = require('./searchHistory');
let chalk = require('chalk');
import chalk from 'chalk';
import { saveHistory } from './searchHistory.mjs';

exports.iciba = (data, options = {}) => {
export const iciba = (data, options = {}) => {
if (options.color === false) {
chalk = initChalkWithNoColor();
}
afc163 marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
26 changes: 13 additions & 13 deletions lib/searchHistory.js → lib/searchHistory.mjs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const fs = require('fs-extra');
const path = require('node:path');
const chalk = require('chalk');
const dayjs = require('dayjs');
import { ensureFileSync, readFileSync, writeFile } from 'node:fs';
import path from 'node:path';
import chalk from 'chalk';
import dayjs from 'dayjs';
import { homedir } from 'node:os';

const homedir = process.env.HOME || require('node:os').homedir();
const searchFilePath = path.resolve(homedir, '.config', 'fanyi', 'searchHistory.txt');

const DAY_SPLIT = 'day-';
Expand Down Expand Up @@ -35,14 +35,14 @@ function getDaySplit(someDay) {
return `${DAY_SPLIT}${someDay}:`;
}

exports.searchList = (args) => {
export const searchList = (args) => {
const { someDay, recentDays, showFile } = args;
console.log();
console.log(chalk.gray('fanyi history:'));
console.log();
let targetContent;
fs.ensureFileSync(searchFilePath);
const data = fs.readFileSync(searchFilePath);
ensureFileSync(searchFilePath);
const data = readFileSync(searchFilePath);
const content = data.toString();
let targetDay = dayjs(someDay).format('YYYY-MM-DD');

Expand Down Expand Up @@ -97,23 +97,23 @@ exports.searchList = (args) => {
}
};

exports.saveHistory = (word, means) => {
export const saveHistory = (word, means) => {
try {
fs.ensureFileSync(searchFilePath);
ensureFileSync(searchFilePath);

const contentBuffer = fs.readFileSync(searchFilePath);
const contentBuffer = readFileSync(searchFilePath);
const content = contentBuffer.toString();
if (content.includes(today)) {
const targetContent = getTargetContent(content, today);
// 去重。当天已经查过的,不再写入
if (targetContent[0].includes(`${word}\n`)) {
return;
}
fs.writeFile(searchFilePath, genWordMean(word, means), { flag: 'a' }, (err) => {
writeFile(searchFilePath, genWordMean(word, means), { flag: 'a' }, (err) => {
if (err) throw err;
});
} else {
fs.writeFile(
writeFile(
searchFilePath,
`${getDaySplit(today)}\n${genWordMean(word, means)}\n`,
{ flag: 'a' },
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,5 +50,6 @@
"prepublishOnly": "np --no-cleanup --no-publish",
"lint-staged": "lint-staged",
"prepare": "husky"
}
},
"type": "module"
}
2 changes: 1 addition & 1 deletion tests/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { fork } from 'node:child_process';
import path from 'node:path';
import { describe, expect, it } from 'vitest';

const scriptPath = path.resolve(__dirname, '../bin/fanyi.js');
const scriptPath = path.resolve(__dirname, '../bin/fanyi.mjs');

const runScript = (args: string[] = []): Promise<{ stdout: string; stderr: string }> => {
return new Promise((resolve, reject) => {
afc163 marked this conversation as resolved.
Show resolved Hide resolved
Expand Down
Loading