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
npm install output-file
const outputFile = require('output-file');
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
})();
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:
Set mode of a file.
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'
})();
- output-file-sync (synchronous version)
ISC License © 2018 - 2019 Shinnosuke Watanabe