output-file

2019-01-13 admin

output-file是什么

什么是output-file,Write a file and create its ancestor directories if needed

output-file使用教程帮助文档

output-file

npm version Build Status Coverage Status

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 and URL
  • An option to set mode of created directories

Installation

Use npm.

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

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.writeFile() and fs.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

License

ISC License © 2018 Shinnosuke Watanabe

你可能感兴趣的文章:

本站文章除注明转载外,均为本站原创或编译。欢迎任何形式的转载,但请务必注明出处。

转载请注明:文章转载自 JavaScript中文网 [https://www.javascriptcn.com]

本文地址:https://www.javascriptcn.com/read-50870.html

文章标题:output-file

回到顶部