Skip to content

Instantly share code, notes, and snippets.

@maraisr
Last active August 9, 2021 00:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maraisr/e36f63d22673da3bc45f08f8cba9e083 to your computer and use it in GitHub Desktop.
Save maraisr/e36f63d22673da3bc45f08f8cba9e083 to your computer and use it in GitHub Desktop.
swrt — Safe Write file

SWRT Safe Write

A safe-write, that classic write the file, but make any folders firstly.

import { write } from 'swrt';

await write('./dist/things.html', '<h1>hello world</h1>');
type FileType = string | Buffer | URL;
type DataType = string | Buffer;
declare function writeFile(path: FileType, body: DataType, content_type?: string): Promise<void>;
declare function writeFileSync(path: FileType, body: DataType, content_type?: string): void;
export { writeFile, writeFileSync };
import { mkdir, writeFile as _writeFile } from "fs/promises";
import { mkdirSync, writeFileSync as _writeFileSync } from "fs";
import { dirname } from "path";
export const writeFile = async (path, body, content_type) => {
content_type = content_type || "utf8";
await mkdir(dirname(path), { recursive: true });
await _writeFile(path, body, content_type);
};
export const writeFileSync = (path, body, content_type) => {
content_type = content_type || "utf8";
mkdirSync(dirname(path), { recursive: true });
_writeFileSync(path, body, content_type);
};
{
"name": "swrt",
"version": "0.0.6",
"repository": "https://gist.github.com/maraisr/e36f63d22673da3bc45f08f8cba9e083",
"license": "MIT",
"author": {
"name": "Marais Rossouw",
"email": "me@marais.dev",
"url": "https://marais.io"
},
"sideEffects": false,
"exports": {
".": {
"import": "./dist/index.mjs",
"require": "./dist/index.js"
},
"./package.json": "./package.json"
},
"main": "dist/index.js",
"module": "dist/index.mjs",
"types": "index.d.ts",
"files": [
"*.d.ts",
"dist"
],
"scripts": {
"build": "bundt index.js"
},
"devDependencies": {
"@types/node": "^16.4.9",
"bundt": "^1.1.5"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment