How to use write-file-atomic - 10 common examples

To help you get started, we’ve selected a few write-file-atomic examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github serverless / serverless / lib / utils / config / index.js View on Github external
function storeConfig(config) {
  try {
    writeFileAtomic.sync(serverlessrcPath, JSON.stringify(config, null, 2));
  } catch (error) {
    if (process.env.SLS_DEBUG) {
      process.stdout.write(`${chalk.red(error.stack)}\n`);
      process.stdout.write(
        `Serverless: ${chalk.red(`Unable to store serverless config due to ${error.code} error`)}\n`
      );
    }
    try {
      return JSON.parse(readFileSync(serverlessrcPath));
    } catch (readError) {
      // Ignore
    }
    return {};
  }
  return config;
}
github sindresorhus / conf / index.js View on Github external
_write(value) {
		let data = this.serialize(value);

		if (this.encryptionKey) {
			const initializationVector = crypto.randomBytes(16);
			const password = crypto.pbkdf2Sync(this.encryptionKey, initializationVector.toString(), 10000, 32, 'sha512');
			const cipher = crypto.createCipheriv(encryptionAlgorithm, password, initializationVector);
			data = Buffer.concat([initializationVector, Buffer.from(':'), cipher.update(Buffer.from(data)), cipher.final()]);
		}

		// Temporary workaround for Conf being packaged in a Ubuntu Snap app.
		// See https://github.com/sindresorhus/conf/pull/82
		if (process.env.SNAP) {
			fs.writeFileSync(this.path, data);
		} else {
			writeFileAtomic.sync(this.path, data);
		}
	}
github netlify / cli / src / base / state / index.js View on Github external
set all(val) {
    try {
      // Make sure the folder exists as it could have been deleted in the meantime
      makeDir.sync(path.dirname(this.path))
      writeFileAtomic.sync(this.path, JSON.stringify(val, null, '\t'))
    } catch (err) {
      // Improve the message of permission errors
      if (err.code === 'EACCES') {
        err.message = `${err.message}\n${permissionError}\n`
      }

      throw err
    }
  }
github avajs / ava / lib / babel-pipeline.js View on Github external
const inputSourceMap = getSourceMap(filename, inputCode);
		if (inputSourceMap) {
			options.inputSourceMap = inputSourceMap;
		}

		const {code, map} = babel.transformSync(inputCode, options);

		if (map) {
			// Save source map
			const mapPath = `${cachePath}.map`;
			writeFileAtomic.sync(mapPath, JSON.stringify(map));

			// Append source map comment to transformed code so that other libraries
			// (like nyc) can find the source map.
			const comment = convertSourceMap.generateMapFileComment(mapPath);
			writeFileAtomic.sync(cachePath, `${code}\n${comment}`);
		} else {
			writeFileAtomic.sync(cachePath, code);
		}

		return cachePath;
	};
}
github yeoman / configstore / index.js View on Github external
try {
			return JSON.parse(fs.readFileSync(this.path, 'utf8'));
		} catch (error) {
			// Create directory if it doesn't exist
			if (error.code === 'ENOENT') {
				return {};
			}

			// Improve the message of permission errors
			if (error.code === 'EACCES') {
				error.message = `${error.message}\n${permissionError}\n`;
			}

			// Empty the file if it encounters invalid JSON
			if (error.name === 'SyntaxError') {
				writeFileAtomic.sync(this.path, '', writeFileOptions);
				return {};
			}

			throw error;
		}
	}
github istanbuljs / caching-transform / index.js View on Github external
onHash(input, metadata, hash);

		let result;
		let retry = 0;
		/* eslint-disable-next-line no-constant-condition */
		while (true) {
			try {
				return fs.readFileSync(cachedPath, encoding);
			} catch (_) {
				if (!result) {
					result = transform(input, metadata, hash);
				}

				try {
					writeFileAtomic.sync(cachedPath, result, {encoding});
					return result;
				} catch (error) {
					/* Likely https://github.com/npm/write-file-atomic/issues/28
					 * Make up to 3 attempts to read or write the cache. */
					retry++;
					if (retry > 3) {
						throw error;
					}
				}
			}
		}
	};
}
github typicode / lowdb / src / adapters / JSONFile.ts View on Github external
this.lock(release => {
        // Write atomically
        writeFileAtomic(this.file, JSON.stringify(data, null, 2), err => {
          // Release file
          release()

          if (err) {
            return reject(err)
          }

          resolve()
        })
      })
    })
github pnpm / pnpm / packages / dependencies-hierarchy / example / node_modules / .registry.npmjs.org / write-json-file / 2.2.0 / node_modules / write-json-file / index.js View on Github external
let indent = opts.indent;

	if (opts.detectIndent) {
		try {
			const file = fs.readFileSync(fp, 'utf8');
			indent = detectIndent(file).indent;
		} catch (err) {
			if (err.code !== 'ENOENT') {
				throw err;
			}
		}
	}

	const json = JSON.stringify(data, opts.replacer, indent);

	return writeFileAtomic.sync(fp, `${json}\n`, {mode: opts.mode});
};
github avajs / ava / lib / snapshot-manager.js View on Github external
}

		const {snapPath} = this;
		const buffer = encodeSnapshots(this.snapshotsByHash);

		const reportPath = path.join(this.dir, this.reportFile);
		const existingReport = this.appendOnly ? tryRead(reportPath) : null;
		const reportBuffer = existingReport ?
			appendReportEntries(existingReport, this.reportEntries) :
			generateReport(this.relFile, this.snapFile, this.reportEntries);

		makeDir.sync(this.dir);

		const paths = [snapPath, reportPath];
		const tmpfileCreated = tmpfile => paths.push(tmpfile);
		writeFileAtomic.sync(snapPath, buffer, {tmpfileCreated});
		writeFileAtomic.sync(reportPath, reportBuffer, {tmpfileCreated});
		return paths;
	}
}
github reruin / sharelist / app / utils / db / filedb.js View on Github external
set all(value) {
    try {
      mkdir(path.dirname(this.path));

      value = JSON.stringify(value);
      if (!this.options.raw) {
        value = base64.encode(value)
      }

      writeFileAtomic.sync(this.path, value);
    } catch (error) {
      throw error;
    }
  }

write-file-atomic

Write files in an atomic fashion w/configurable ownership

ISC
Latest version published 2 months ago

Package Health Score

92 / 100
Full package analysis

Popular write-file-atomic functions