mono/packages/fs/dist/write.js
2025-02-21 12:15:15 +01:00

83 lines
3.0 KiB
JavaScript

import * as pathUtil from 'path';
import * as fs from 'fs';
import { writeFileSync } from 'fs';
import { sync as mkdirp } from 'mkdirp';
import { json, file } from './imports.js';
import { validateArgument, validateOptions } from './utils/validate.js';
import { promisify } from './promisify.js';
const newExt = '.__new__';
export function validateInput(methodName, path, data, options) {
const methodSignature = methodName + '(path, data, [options])';
validateArgument(methodSignature, 'path', path, ['string']);
validateArgument(methodSignature, 'data', data, ['string', 'buffer', 'object', 'array']);
validateOptions(methodSignature, 'options', options, {
atomic: ['boolean'],
jsonIndent: ['number'],
progress: ['function']
});
}
const toJson = (data, jsonIndent) => {
if (typeof data === 'object'
&& !Buffer.isBuffer(data)
&& data !== null) {
return json.serialize(data, null, typeof jsonIndent !== 'number' ? 2 : jsonIndent);
}
return data;
};
// ---------------------------------------------------------
// SYNC
// ---------------------------------------------------------
const _writeFileSync = (path, data, options) => {
try {
writeFileSync(path, data, options);
}
catch (err) {
if (err.code === 'ENOENT') {
// Means parent directory doesn't exist, so create it and try again.
mkdirp(pathUtil.dirname(path));
fs.writeFileSync(path, data, options);
}
else {
throw err;
}
}
};
const writeAtomicSync = (path, data, options) => {
return file.write_atomic(path + newExt, data, options, function () { });
};
export function sync(path, data, options) {
const opts = options || {};
const processedData = toJson(data, opts.jsonIndent);
const writeStrategy = opts.atomic ? writeAtomicSync : _writeFileSync;
writeStrategy(path, processedData, { mode: opts.mode });
}
// ---------------------------------------------------------
// ASYNC
// ---------------------------------------------------------
const promisedWriteFile = fs.promises.writeFile;
const promisedAtomic = promisify(writeAtomicSync);
function writeFileAsync(path, data, options) {
return new Promise((resolve, reject) => {
promisedWriteFile(path, data, options)
.then(resolve)
.catch((err) => {
// First attempt to write a file ended with error.
// Check if this is not due to nonexistent parent directory.
if (err.code === 'ENOENT') {
// Parent directory doesn't exist, so create it and try again.
mkdirp(pathUtil.dirname(path));
promisedWriteFile(path, data, options);
resolve();
}
else {
reject(err);
}
});
});
}
export function async(path, data, options) {
const opts = options || {};
const processedData = toJson(data, opts.jsonIndent);
return (opts.atomic ? promisedAtomic : writeFileAsync)(path, processedData, { mode: opts.mode });
}