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 string/buffer to a random temp file
Install
$ npm install --save temp-write
Usage
const fs = require('fs');
const tempWrite = require('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(input, [filepath])
Returns a promise that resolves to the filepath of the temp file.
tempWrite.sync(input, [filepath])
Returns the filepath of the temp file.
input
Type: string
, buffer
filepath
Type: string
Example: 'img.png'
, 'foo/bar/baz.png'
Optionally supply a filepath which is appended to the random path.
Related
License
MIT © Sindre Sorhus