Skip to content

Commit 532be0c

Browse files
Richienbsindresorhus
andauthoredMar 9, 2020
Add methods for writing data to temp files (#22)
Co-authored-by: Sindre Sorhus <sindresorhus@gmail.com>
1 parent a2c7198 commit 532be0c

File tree

6 files changed

+131
-2
lines changed

6 files changed

+131
-2
lines changed
 

‎index.d.ts

+28-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import {MergeExclusive} from 'type-fest';
1+
/// <reference types="node"/>
2+
import {MergeExclusive, TypedArray} from 'type-fest';
23

34
declare namespace tempy {
45
type Options = MergeExclusive<
@@ -61,6 +62,32 @@ declare const tempy: {
6162
*/
6263
directory(): string;
6364

65+
/**
66+
Write data to a random temp file.
67+
68+
@example
69+
```
70+
import tempy = require('tempy');
71+
72+
await tempy.write('🦄');
73+
//=> '/private/var/folders/3x/jf5977fn79jbglr7rk0tq4d00000gn/T/2f3d094aec2cb1b93bb0f4cffce5ebd6'
74+
```
75+
*/
76+
write(fileContent: string | Buffer | TypedArray | DataView | NodeJS.ReadableStream, options?: tempy.Options): Promise<string>;
77+
78+
/**
79+
Synchronously write data to a random temp file.
80+
81+
@example
82+
```
83+
import tempy = require('tempy');
84+
85+
tempy.writeSync('🦄');
86+
//=> '/private/var/folders/3x/jf5977fn79jbglr7rk0tq4d00000gn/T/2f3d094aec2cb1b93bb0f4cffce5ebd6'
87+
```
88+
*/
89+
writeSync(fileContent: string | Buffer | TypedArray | DataView, options?: tempy.Options): string;
90+
6491
/**
6592
Get the root temporary directory path.
6693

‎index.js

+21
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,17 @@ const fs = require('fs');
33
const path = require('path');
44
const uniqueString = require('unique-string');
55
const tempDir = require('temp-dir');
6+
const isStream = require('is-stream');
7+
const stream = require('stream');
8+
const {promisify} = require('util');
9+
10+
const pipeline = promisify(stream.pipeline);
11+
const {writeFile} = fs.promises;
612

713
const getPath = () => path.join(tempDir, uniqueString());
814

15+
const writeStream = async (filePath, data) => pipeline(data, fs.createWriteStream(filePath));
16+
917
module.exports.file = options => {
1018
options = {
1119
...options
@@ -28,6 +36,19 @@ module.exports.directory = () => {
2836
return directory;
2937
};
3038

39+
module.exports.write = async (data, options) => {
40+
const filename = module.exports.file(options);
41+
const write = isStream(data) ? writeStream : writeFile;
42+
await write(filename, data);
43+
return filename;
44+
};
45+
46+
module.exports.writeSync = (data, options) => {
47+
const filename = module.exports.file(options);
48+
fs.writeFileSync(filename, data);
49+
return filename;
50+
};
51+
3152
Object.defineProperty(module.exports, 'root', {
3253
get() {
3354
return tempDir;

‎index.test-d.ts

+9
Original file line numberDiff line numberDiff line change
@@ -8,3 +8,12 @@ expectType<string>(tempy.file({extension: 'png'}));
88
expectType<string>(tempy.file({name: 'afile.txt'}));
99
expectError(tempy.file({extension: 'png', name: 'afile.txt'}));
1010
expectType<string>(tempy.root);
11+
12+
expectType<Promise<string>>(tempy.write('unicorn'));
13+
expectType<Promise<string>>(tempy.write('unicorn', {name: 'pony.png'}));
14+
expectType<Promise<string>>(tempy.write(process.stdin, {name: 'pony.png'}));
15+
expectType<Promise<string>>(tempy.write(new Buffer('pony'), {name: 'pony.png'}));
16+
17+
expectType<string>(tempy.writeSync('unicorn'));
18+
expectType<string>(tempy.writeSync(new Buffer('unicorn')));
19+
expectType<string>(tempy.writeSync('unicorn', {name: 'pony.png'}));

‎package.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,9 @@
3535
"unique"
3636
],
3737
"dependencies": {
38+
"is-stream": "^2.0.0",
3839
"temp-dir": "^2.0.0",
39-
"type-fest": "^0.10.0",
40+
"type-fest": "^0.11.0",
4041
"unique-string": "^2.0.0"
4142
},
4243
"devDependencies": {

‎readme.md

+28
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,34 @@ Filename. Mutually exclusive with the `extension` option.
5454

5555
Get a temporary directory path. The directory is created for you.
5656

57+
### tempy.write(fileContent, options?)
58+
59+
Write data to a random temp file.
60+
61+
##### fileContent
62+
63+
Type: `string | Buffer | TypedArray | DataView | stream.Readable`
64+
65+
Data to write to the temp file.
66+
67+
##### options
68+
69+
See [options](#options).
70+
71+
### tempy.writeSync(fileContent, options?)
72+
73+
Synchronously write data to a random temp file.
74+
75+
##### fileContent
76+
77+
Type: `string | Buffer | TypedArray | DataView`
78+
79+
Data to write to the temp file.
80+
81+
##### options
82+
83+
See [options](#options).
84+
5785
### tempy.root
5886

5987
Get the root temporary directory path. For example: `/private/var/folders/3x/jf5977fn79jbglr7rk0tq4d00000gn/T`

‎test.js

+43
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
import path from 'path';
22
import {tmpdir} from 'os';
3+
import fs from 'fs';
4+
import stream from 'stream';
35
import test from 'ava';
46
import tempy from '.';
57

@@ -34,9 +36,50 @@ test('.directory()', t => {
3436
t.true(tempy.directory().includes(tmpdir()));
3537
});
3638

39+
test('.write(string)', async t => {
40+
const filePath = await tempy.write('unicorn', {name: 'test.png'});
41+
t.is(fs.readFileSync(filePath, 'utf8'), 'unicorn');
42+
t.is(path.basename(filePath), 'test.png');
43+
});
44+
45+
test('.write(buffer)', async t => {
46+
const filePath = await tempy.write(Buffer.from('unicorn'));
47+
t.is(fs.readFileSync(filePath, 'utf8'), 'unicorn');
48+
});
49+
50+
test('.write(stream)', async t => {
51+
const readable = new stream.Readable({
52+
read() {}
53+
});
54+
readable.push('unicorn');
55+
readable.push(null);
56+
const filePath = await tempy.write(readable);
57+
t.is(fs.readFileSync(filePath, 'utf8'), 'unicorn');
58+
});
59+
60+
test('.write(stream) failing stream', async t => {
61+
const readable = new stream.Readable({
62+
read() {}
63+
});
64+
readable.push('unicorn');
65+
setImmediate(() => {
66+
readable.emit('error', new Error('Catch me if you can!'));
67+
readable.push(null);
68+
});
69+
await t.throwsAsync(() => tempy.write(readable), {
70+
instanceOf: Error,
71+
message: 'Catch me if you can!'
72+
});
73+
});
74+
75+
test('.writeSync()', t => {
76+
t.is(fs.readFileSync(tempy.writeSync('unicorn'), 'utf8'), 'unicorn');
77+
});
78+
3779
test('.root', t => {
3880
t.true(tempy.root.length > 0);
3981
t.true(path.isAbsolute(tempy.root));
82+
4083
t.throws(() => {
4184
tempy.root = 'foo';
4285
});

0 commit comments

Comments
 (0)
Please sign in to comment.