UNPKG

2.69 kBJavaScriptView Raw
1import fs from 'node:fs'
2import os from 'node:os'
3import randomPath from 'random-path'
4
5import { retryAsync, retrySync } from './retry.js'
6import WriteStream from './write-stream.js'
7
8const tmpdir = os.tmpdir()
9
10export function open (template, flags, mode, cb) {
11 switch (flags) {
12 case 'w': flags = 'wx'; break
13 case 'w+': flags = 'wx+'; break
14 default: throw new Error('Unknown file open flag: ' + flags)
15 }
16
17 if (typeof mode === 'function') {
18 cb = mode
19 mode = undefined
20 }
21
22 let path
23
24 retryAsync(function (cb) {
25 path = randomPath(tmpdir, template)
26 fs.open(path, flags, mode, cb)
27 }, function (err, fd) {
28 cb(err, err ? undefined : { fd, path })
29 })
30}
31
32export function openSync (template, flags, mode) {
33 switch (flags) {
34 case 'w': flags = 'wx'; break
35 case 'w+': flags = 'wx+'; break
36 default: throw new Error('Unknown file open flag: ' + flags)
37 }
38
39 let path
40
41 const fd = retrySync(function () {
42 path = randomPath(tmpdir, template)
43 return fs.openSync(path, flags, mode)
44 })
45
46 return { fd, path }
47}
48
49export function mkdir (template, mode, cb) {
50 if (typeof mode === 'function') {
51 cb = mode
52 mode = undefined
53 }
54
55 let path
56
57 retryAsync(function (cb) {
58 path = randomPath(tmpdir, template)
59 fs.mkdir(path, mode, cb)
60 }, function (err) {
61 cb(err, err ? undefined : path)
62 })
63}
64
65export function mkdirSync (template, mode) {
66 let path
67
68 retrySync(function () {
69 path = randomPath(tmpdir, template)
70 fs.mkdirSync(path, mode)
71 })
72
73 return path
74}
75
76export function writeFile (template, data, options, cb) {
77 cb = arguments[arguments.length - 1]
78
79 if (typeof options === 'function' || !options) {
80 options = { flag: 'wx' }
81 } else if (typeof options === 'string') {
82 options = { encoding: options, flag: 'wx' }
83 } else if (typeof options === 'object') {
84 options.flag = 'wx'
85 } else {
86 throw new TypeError('Bad arguments')
87 }
88
89 let path
90
91 retryAsync(function (cb) {
92 path = randomPath(tmpdir, template)
93 fs.writeFile(path, data, options, cb)
94 }, function (err) {
95 cb(err, err ? undefined : path)
96 })
97}
98
99export function writeFileSync (template, data, options) {
100 if (!options) {
101 options = { flag: 'wx' }
102 } else if (typeof options === 'string') {
103 options = { encoding: options, flag: 'wx' }
104 } else if (typeof options === 'object') {
105 options.flag = 'wx'
106 } else {
107 throw new TypeError('Bad arguments')
108 }
109
110 let path
111
112 retrySync(function () {
113 path = randomPath(tmpdir, template)
114 fs.writeFileSync(path, data, options)
115 })
116
117 return path
118}
119
120export function createWriteStream (template, options) {
121 return new WriteStream(template, options)
122}