What is temp-write?
The temp-write npm package allows you to write temporary files to the filesystem. It is useful for scenarios where you need to create temporary files that are automatically cleaned up after use.
What are temp-write's main functionalities?
Write temporary file with content
This feature allows you to write a string to a temporary file and get the file path. The file is automatically cleaned up after the process exits.
const tempWrite = require('temp-write');
const fs = require('fs');
(async () => {
const filePath = await tempWrite('Hello, world!');
console.log(filePath);
console.log(fs.readFileSync(filePath, 'utf8'));
})();
Write temporary file with specific extension
This feature allows you to specify the extension of the temporary file. The file is automatically cleaned up after the process exits.
const tempWrite = require('temp-write');
const fs = require('fs');
(async () => {
const filePath = await tempWrite('Hello, world!', { extension: 'txt' });
console.log(filePath);
console.log(fs.readFileSync(filePath, 'utf8'));
})();
Write temporary file with specific name
This feature allows you to specify the name of the temporary file. The file is automatically cleaned up after the process exits.
const tempWrite = require('temp-write');
const fs = require('fs');
(async () => {
const filePath = await tempWrite('Hello, world!', { name: 'example.txt' });
console.log(filePath);
console.log(fs.readFileSync(filePath, 'utf8'));
})();
Other packages similar to temp-write
tmp
The tmp package provides similar functionality for creating temporary files and directories. It offers more control over the lifecycle of the temporary files and directories, including manual cleanup.
temp
The temp package is another alternative for handling temporary files and directories. It provides a more comprehensive API for managing temporary resources, including automatic cleanup and custom directory support.
fs-extra
The fs-extra package extends the native fs module with additional methods, including methods for handling temporary files. It provides a more extensive set of file system utilities beyond just temporary file handling.
temp-write
Write data to a random temporary file
Install
npm install temp-write
Usage
import fs from 'node:fs';
import tempWrite from 'temp-write';
const filePath = tempWrite.sync('unicorn');
fs.readFileSync(filePath, 'utf8');
tempWrite.sync('unicorn', 'pony.png');
tempWrite.sync('unicorn', 'rainbow/cake/pony.png');
API
tempWrite(fileContent, filePath?)
Returns a Promise
for the file path of the temporary file.
tempWrite.sync(fileContent, filePath?)
Returns the file path of the temporary file.
fileContent
Type: string | Uint8Array | stream.Readable
The data to write to the temporary file. Streams are supported only with the async API.
filePath
Type: string
Examples: 'img.png'
'foo/bar/baz.png'
Optionally specify a file path which is appended to the random path.
Related
- tempy - Get a random temporary file or directory path