fs-extender
Version:
Extras suite for node fs module
410 lines • 16.6 kB
JavaScript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __asyncValues = (this && this.__asyncValues) || function (o) {
if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
var m = o[Symbol.asyncIterator], i;
return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.readJsonLines = exports.readJsonFileSync = exports.promises = exports.readJsonFile = exports.ensureJsonFileSync = exports.writeJsonFileSync = exports.ensureJsonFile = exports.writeJsonFile = void 0;
const fs = __importStar(require("../patch"));
const util = __importStar(require("../util"));
const ensure = __importStar(require("../ensure"));
const utils_1 = require("@n3okill/utils");
const readline = __importStar(require("readline"));
/** @internal */
function getWriteOptions(opt = {}) {
return {
EOL: util.getObjectOption(opt, "EOL", "\n"),
finalEOL: util.getObjectOption(opt, "finalEOL", true),
replacer: util.getObjectOption(opt, "replacer", null),
spaces: util.getObjectOption(opt, "spaces", null),
encoding: util.getObjectOption(opt, "encoding", "utf8"),
mode: util.getObjectOption(opt, "mode", 0o666),
flag: util.getObjectOption(opt, "flag", "wx"),
};
}
/** @internal */
function getReadOptions(opt = {}) {
const options = getReadLineOptions(opt);
options.flag = util.getObjectOption(opt, "flag", "r");
return options;
}
/** @internal */
function getReadLineOptions(opt = {}) {
return {
encoding: util.getObjectOption(opt, "encoding", "utf8"),
throws: util.getObjectOption(opt, "throws", true),
reviver: util.getObjectOption(opt, "reviver", undefined),
};
}
function writeJsonFile(path, obj, options, callback) {
const opt = getWriteOptions(options);
const cb = util.getCallback(options, callback);
_writeJsonFile(path, obj, opt)
.then((p) => cb(null, p))
.catch((err) => cb(err));
}
exports.writeJsonFile = writeJsonFile;
/** @internal */
function _writeJsonFile(path, obj, options) {
return __awaiter(this, void 0, void 0, function* () {
const str = stringify(obj, options);
yield fs.promises.writeFile(path, str, {
encoding: options.encoding,
mode: options.mode,
flag: options.flag,
});
return path;
});
}
function ensureJsonFile(path, obj, options, callback) {
const opt = getWriteOptions(options);
const cb = util.getCallback(options, callback);
_ensureJsonFile(path, obj, opt)
.then((p) => cb(null, p))
.catch((err) => cb(err));
}
exports.ensureJsonFile = ensureJsonFile;
/** @internal */
function _ensureJsonFile(path, obj, options) {
return __awaiter(this, void 0, void 0, function* () {
const str = stringify(obj, options);
return ensure.promises.ensureFile(path, {
data: str,
encoding: options.encoding,
mode: options.mode,
flag: options.flag,
});
});
}
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string and write it to a file
*
* ```js
* import * as fs from "fs-extender"
* fs.writeJsonFileSync(path,{name:'Jonh Smith', age:1001});
* console.log(`File writed with success`);
* ```
*
* @param path - fs.PathLike
* @param obj - object to write to file as json string
* @param options - options
* - `EOL` - End Of Line character default: `\n`
* - `finalEOL` - Use EOL character at the end of the file, default: `true`
* - `replacer` - The replacer function to use when transforming object to json, default: `null`, no replacer used
* - `spaces` - The number of spaces to use as identation, default: `null`, o spaces used
* - `encoding` - The encoding used to write the file, default: `utf8`
* - `mode` - The mode used to for the file, default: `0o666`
* - `flag` - Flag to be used when writing the file, default: `wx`, Open file for writing but fails if path exists
* @return `fs.PathLike`
*/
function writeJsonFileSync(path, obj, options) {
const opt = getWriteOptions(options);
const str = stringify(obj, opt);
fs.writeFileSync(path, str, opt);
return path;
}
exports.writeJsonFileSync = writeJsonFileSync;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string and write it
* to a file making sure the file is created even if the path doesn't exist
* This works as a mix between @see[writeJsonFileSync] and @see[ensureFileSync]
*
* ```js
* import * as fs from "fs-extender"
* fs.ensureJsonFileSync(path,{name:'Jonh Smith', age:1001});
* console.log(`File writed with success`);
* ```
*
* @param path - fs.PathLike
* @param obj - object to write to file as json string
* @param options - options
* - `EOL` - End Of Line character default: `\n`
* - `finalEOL` - Use EOL character at the end of the file, default: `true`
* - `replacer` - The replacer function to use when transforming object to json, default: `null`, no replacer used
* - `spaces` - The number of spaces to use as identation, default: `null`, o spaces used
* - `encoding` - The encoding used to write the file, default: `utf8`
* - `mode` - The mode used to for the file, default: `0o666`
* - `flag` - Flag to be used when writing the file, default: `wx`, Open file for writing but fails if path exists
* @return `fs.PathLike`
*/
function ensureJsonFileSync(path, obj, options) {
const opt = getWriteOptions(options);
const str = stringify(obj, opt);
return ensure.ensureFileSync(path, {
data: str,
encoding: opt.encoding,
mode: opt.mode,
flag: opt.flag,
});
}
exports.ensureJsonFileSync = ensureJsonFileSync;
/** @internal */
function stringify(obj, options) {
const EOF = options.finalEOL ? options.EOL : "";
const str = JSON.stringify(obj, options.replacer, options.spaces);
return str.replace(/\n/g, options.EOL) + EOF;
}
function readJsonFile(path, options, callback) {
const opt = getReadOptions(options);
const cb = util.getCallback(options, callback);
_readJsonFile(path, opt)
.then((res) => cb(null, res))
.catch((err) => cb(err));
}
exports.readJsonFile = readJsonFile;
/** @internal */
function _readJsonFile(path, options) {
return __awaiter(this, void 0, void 0, function* () {
try {
let content = yield fs.promises.readFile(path, {
encoding: options.encoding,
flag: options.flag,
});
content = stripBom(content);
return JSON.parse(content, options.reviver);
}
catch (err) {
if (options.throws) {
err.message = `${path}: ${err.message}`;
throw err;
}
return undefined;
}
});
}
// eslint-disable-next-line @typescript-eslint/no-namespace
var promises;
(function (promises) {
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string and write it to a file
*
* ```js
* import * as fs from "fs-extender"
* await fs.promises.writeJsonFile(path,{name:'Jonh Smith', age:1001});
* console.log(`File writed with success`);
* ```
*
* @param path - fs.PathLike
* @param obj - object to write to file as json string
* @param options - options
* - `EOL` - End Of Line character default: `\n`
* - `finalEOL` - Use EOL character at the end of the file, default: `true`
* - `replacer` - The replacer function to use when transforming object to json, default: `null`, no replacer used
* - `spaces` - The number of spaces to use as identation, default: `null`, o spaces used
* - `encoding` - The encoding used to write the file, default: `utf8`
* - `mode` - The mode used to for the file, default: `0o666`
* - `flag` - Flag to be used when writing the file, default: `wx`, Open file for writing but fails if path exists
* @return `Promise<fs.PathLike>`
*/
function writeJsonFile(path, obj, options) {
return __awaiter(this, void 0, void 0, function* () {
const opt = getWriteOptions(options);
return _writeJsonFile(path, obj, opt);
});
}
promises.writeJsonFile = writeJsonFile;
/**
* Converts a JavaScript value to a JavaScript Object Notation (JSON) string and write it
* to a file making sure the file is created even if the path doesn't exist
* This works as a mix between @see[writeJsonFile] and @see[ensureFile]
*
* ```js
* import * as fs from "fs-extender"
* await fs.promises.ensureJsonFile(path,{name:'Jonh Smith', age:1001});
* console.log(`File writed with success`);
* ```
*
* @param path - fs.PathLike
* @param obj - object to write to file as json string
* @param options - options
* - `EOL` - End Of Line character default: `\n`
* - `finalEOL` - Use EOL character at the end of the file, default: `true`
* - `replacer` - The replacer function to use when transforming object to json, default: `null`, no replacer used
* - `spaces` - The number of spaces to use as identation, default: `null`, o spaces used
* - `encoding` - The encoding used to write the file, default: `utf8`
* - `mode` - The mode used to for the file, default: `0o666`
* - `flag` - Flag to be used when writing the file, default: `wx`, Open file for writing but fails if path exists
* @return `Promise<fs.PathLike>`
*/
function ensureJsonFile(path, obj, options) {
return __awaiter(this, void 0, void 0, function* () {
const opt = getWriteOptions(options);
return _ensureJsonFile(path, obj, opt);
});
}
promises.ensureJsonFile = ensureJsonFile;
/**
* Read json file and transform's it into an object
*
* ```js
* import * as fs from "fs-extender"
* const obj = await fs.promises.readJsonFile(path);
* console.log(`File read with success. Object: ${obj}`);
* ```
*
* @param path - fs.pathLike
* @param options - options
* - `flag` - flag used to open the file, default: `r`
* - `encoding` - `BufferEncoding` used to read the file, default: `utf8`
* - `throws` - should throw if an error occur, default: `true`
* - `reviver` Reviver function used to parse the json string, default: `undefined`
* @return `Promise<any>`
*/
function readJsonFile(path, options) {
return __awaiter(this, void 0, void 0, function* () {
const opt = getReadOptions(options);
return _readJsonFile(path, opt);
});
}
promises.readJsonFile = readJsonFile;
function readJsonLines(path, options, fn) {
return __awaiter(this, void 0, void 0, function* () {
let caller = fn, opt;
if (utils_1.Type.isFunction(options)) {
caller = options;
opt = getReadLineOptions();
}
else {
opt = getReadLineOptions(options);
}
return _readJsonLines(path, opt, caller);
});
}
promises.readJsonLines = readJsonLines;
})(promises = exports.promises || (exports.promises = {}));
/**
* Read json file and transform's it into an object
*
* ```js
* import * as fs from "fs-extender"
* const obj = fs.readJsonFileSync(path);
* console.log(`File read with success. Object: ${obj}`);
* ```
*
* @param path - fs.pathLike
* @param options - options
* - `flag` - flag used to open the file, default: `r`
* - `encoding` - `BufferEncoding` used to read the file, default: `utf8`
* - `throws` - should throw if an error occur, default: `true`
* - `reviver` Reviver function used to parse the json string, default: `undefined`
* @return `any`
*/
function readJsonFileSync(path, options) {
const opt = getReadOptions(options);
try {
let content = fs.readFileSync(path, {
encoding: opt.encoding,
flag: opt.flag,
});
content = stripBom(content);
return JSON.parse(content, opt.reviver);
}
catch (err) {
if (opt.throws) {
err.message = `${path}: ${err.message}`;
throw err;
}
return undefined;
}
}
exports.readJsonFileSync = readJsonFileSync;
/** @internal */
function stripBom(content) {
if (Buffer.isBuffer(content)) {
return content.toString("utf8").replace(/^\uFEFF/, "");
}
return content.replace(/^\uFEFF/, "");
}
function readJsonLines(path, options, fn, callback) {
let caller, cb, opt;
if (utils_1.Type.isFunction(options)) {
caller = options;
cb = fn;
opt = getReadLineOptions();
}
else {
opt = getReadLineOptions(options);
caller = fn;
cb = callback;
}
_readJsonLines(path, opt, caller)
.then(() => cb(null))
.catch((err) => cb(err));
}
exports.readJsonLines = readJsonLines;
/** @internal */
function _readJsonLines(path, options, fn) {
var e_1, _a;
return __awaiter(this, void 0, void 0, function* () {
let counter = 0;
try {
yield fs.promises.stat(path);
}
catch (err) {
if (options.throws) {
err.message = err.message.replace(/stat/, "readJsonLines");
throw err;
}
return;
}
const reader = readline.createInterface({
input: fs.createReadStream(path, { encoding: options.encoding }),
});
try {
for (var reader_1 = __asyncValues(reader), reader_1_1; reader_1_1 = yield reader_1.next(), !reader_1_1.done;) {
const line = reader_1_1.value;
try {
const content = JSON.parse(line, options.reviver);
if (!(yield fn(content))) {
return;
}
}
catch (err) {
if (options.throws) {
err.message = `Line: '${counter++}' ${err.message}`;
throw err;
}
}
}
}
catch (e_1_1) { e_1 = { error: e_1_1 }; }
finally {
try {
if (reader_1_1 && !reader_1_1.done && (_a = reader_1.return)) yield _a.call(reader_1);
}
finally { if (e_1) throw e_1.error; }
}
});
}
//# sourceMappingURL=index.js.map
;