output-file v2.0.2
output-file
Write a file and create its ancestor directories if needed
const {readFile} = require('fs').promises;
const outputFile = require('output-file');
(async () => {
await outputFile('foo/bar/baz.txt', 'Hi!');
await readFile('foo/bar/baz.txt', 'utf8'); //=> 'Hi!'
})();
This module is very similar to fs-extra's fs.outputFile
, but has the following features fs-extra doesn't have:
- Support for various non-string path types –
Buffer
,Uint8Array
andURL
- An option to set mode of created directories
Installation
npm install output-file
API
const outputFile = require('output-file');
outputFile(path, data , options)
path: string | Buffer | Uint8Array | URL
data: string | Buffer | TypedArray | DataView
options: Object
(options) or string
(file encoding)
Return: Promise<undefined>
It writes the data to a file asynchronously. If ancestor directories of a file don't exist, it creates those directories before writing a file.
const {stat} = require('fs').promises;
const outputFile = require('output-file');
// When the directory `foo/bar` exists
(async () => {
await outputFile('foo/bar/baz/qux.txt', 'Hello');
(await stat('foo/bar/baz')).isDirectory(); //=> true
(await stat('foo/bar/baz/qux.txt')).isFile(); //=> true
})();
options
All options for fs.promises.writeFile()
and fs.promises.mkdir()
, except for mode
and recursive
, are supported.
recursive
option is enabled by default and cannot be disabled.
Instead of mode
option, use the followings:
options.fileMode
Set mode of a file.
options.dirMode
Set mode of directories.
const {stat} = require('fs').promises;
const outputFile = require('output-file');
(async () => {
await outputFile('dir/file', 'content', {
dirMode: '0745',
fileMode: '0644'
});
(await stat('dir')).mode.toString(8); //=> '40745'
(await stat('dir/file')).mode.toString(8); //=> '100644'
})();
Related project
- output-file-sync (synchronous version)
License
ISC License © 2018 - 2019 Shinnosuke Watanabe
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
10 years ago
10 years ago
10 years ago
10 years ago