mihawk
Version:
A tiny & simple mock server tool, support json,js,cjs,ts(typescript).
89 lines (88 loc) • 2.89 kB
JavaScript
import { isAbsolute, resolve, dirname } from 'path';
import Colors from 'color-cc';
import * as JSON5 from 'json5';
import { writeFileSync, writeJSONSync, existsSync, ensureDirSync, readFileSync } from 'fs-extra';
import { CWD } from '../consts';
export function writeFileSafeSync(filePath, data, options) {
if (!filePath) {
return;
}
filePath = isAbsolute(filePath) ? filePath : resolve(CWD, filePath);
const dirPath = dirname(filePath);
if (!existsSync(dirPath)) {
ensureDirSync(dirPath);
}
options = typeof options === 'string' ? { encoding: options } : options;
writeFileSync(filePath, data, { encoding: 'utf-8', ...options });
}
export function writeJSONSafeSync(jsonFilePath, obj, options) {
if (!jsonFilePath) {
return;
}
jsonFilePath = isAbsolute(jsonFilePath) ? jsonFilePath : resolve(CWD, jsonFilePath);
const dirPath = dirname(jsonFilePath);
if (!existsSync(dirPath)) {
ensureDirSync(dirPath);
}
options = typeof options === 'string' ? { encoding: options } : options;
writeJSONSync(jsonFilePath, obj, { spaces: 2, encoding: 'utf-8', ...options });
}
export function readFileSafeSync(filePath, options) {
if (!filePath) {
return '';
}
filePath = isAbsolute(filePath) ? filePath : resolve(CWD, filePath);
if (!existsSync(filePath)) {
console.log(Colors.warn(`The target file path is not existed!`), filePath);
return '';
}
let opts = { encoding: 'utf-8' };
const typeOfOptions = typeof options;
if (typeOfOptions === 'object' && options !== null) {
opts = {
...opts,
...options,
};
}
if (typeOfOptions === 'string') {
opts.encoding = options;
}
try {
return readFileSync(filePath, opts);
}
catch (error) {
console.log(Colors.warn(`Read file error! filePath=${filePath}`), error);
return '';
}
}
export function readJsonSafeSync(jsonFilePath, options) {
if (!jsonFilePath) {
return null;
}
let json = null;
jsonFilePath = isAbsolute(jsonFilePath) ? jsonFilePath : resolve(CWD, jsonFilePath);
if (!existsSync(jsonFilePath)) {
console.log(Colors.warn(`The target file path is not existed!`), jsonFilePath);
return json;
}
let opts = { encoding: 'utf-8' };
const typeOfOptions = typeof options;
if (typeOfOptions === 'object' && options !== null) {
opts = {
...opts,
...options,
};
}
if (typeOfOptions === 'string') {
opts.encoding = options;
}
try {
const content = readFileSync(jsonFilePath, opts);
json = JSON5.parse(content);
}
catch (error) {
console.error(Colors.error(`Parse JsonFile Error: ${jsonFilePath}`), error, '\n');
json = {};
}
return json;
}