Coder Social home page Coder Social logo

jonschlinkert / write Goto Github PK

View Code? Open in Web Editor NEW
82.0 6.0 8.0 66 KB

Write data to the file system, creating any intermediate directories if they don't already exist. Used by flat-cache and many others!

Home Page: https://github.com/jonschlinkert

License: MIT License

JavaScript 100.00%
fs write writefile writefilesync file-system file stream disk sync async

write's Introduction

write Donate NPM version NPM monthly downloads NPM total downloads Build Status

Write data to a file, replacing the file if it already exists and creating any intermediate directories if they don't already exist. Thin wrapper around node's native fs methods.

Please consider following this project's author, Jon Schlinkert, and consider starring the project to show your ❤️ and support.

Install

Install with npm (requires Node.js >=10):

$ npm install --save write

Usage

const write = require('write');

Options

The following options may be used with any method.

options.newline

Type: boolean

Default: undefined

Ensure that contents has a trailing newline before writing it to the file system.

write.sync('foo.txt', 'some data...', { newline: true }); 

options.overwrite

Type: boolean

Default: undefined

Set to false to prevent existing files from being overwritten. See increment for a less severe alternative.

write.sync('foo.txt', 'some data...', { overwrite: false });

options.increment

Type: boolean

Default: undefined

Set to true to automatically rename files by appending an increment, like foo (2).txt, to prevent foo.txt from being overwritten. This is useful when writing log files, or other information where the file name is less important than the contents being written.

write.sync('foo.txt', 'some data...', { increment: true });
// if "foo.txt" exists, the file will be renamed to "foo (2).txt"

API

Asynchronously writes data to a file, replacing the file if it already exists and creating any intermediate directories if they don't already exist. Data can be a string or a buffer. Returns a promise if a callback function is not passed.

Params

  • filepath {String}: file path.
  • data {String|Buffer|Uint8Array}: Data to write.
  • options {Object}: Options to pass to fs.writeFile
  • callback {Function}: (optional) If no callback is provided, a promise is returned.
  • returns {Object}: Returns an object with the path and contents of the file that was written to the file system. This is useful for debugging when options.increment is used and the path might have been modified.

Example

const write = require('write');

// async/await
(async () => {
  await write('foo.txt', 'This is content...');
})();

// promise
write('foo.txt', 'This is content...')
  .then(() => {
    // do stuff
  });

// callback
write('foo.txt', 'This is content...', err => {
  // do stuff with err
});

The synchronous version of write. Returns undefined.

Params

  • filepath {String}: file path.
  • data {String|Buffer|Uint8Array}: Data to write.
  • options {Object}: Options to pass to fs.writeFileSync
  • returns {Object}: Returns an object with the path and contents of the file that was written to the file system. This is useful for debugging when options.increment is used and the path might have been modified.

Example

const write = require('write');
write.sync('foo.txt', 'This is content...');

Returns a new WriteStream object. Uses fs.createWriteStream to write data to a file, replacing the file if it already exists and creating any intermediate directories if they don't already exist. Data can be a string or a buffer.

Params

Example

const fs = require('fs');
const write = require('write');
fs.createReadStream('README.md')
  .pipe(write.stream('a/b/c/other-file.md'))
  .on('close', () => {
    // do stuff
  });

Release history

See [CHANGELOG.md].

About

Contributing

Pull requests and stars are always welcome. For bugs and feature requests, please create an issue.

Running Tests

Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command:

$ npm install && npm test
Building docs

(This project's readme.md is generated by verb, please don't edit the readme directly. Any changes to the readme must be made in the .verb.md readme template.)

To generate the readme, run the following command:

$ npm install -g verbose/verb#dev verb-generate-readme && verb

Related projects

You might also be interested in these projects:

Contributors

Commits Contributor
42 jonschlinkert
2 jpetitcolas
1 tunnckoCore

Author

Jon Schlinkert

License

Copyright © 2019, Jon Schlinkert. Released under the MIT License.


This file was generated by verb-generate-readme, v0.8.0, on September 04, 2019.

write's People

Contributors

jonschlinkert avatar jpetitcolas avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

write's Issues

Namespace '"fs"' has no exported members - Error

I am running Node 12.14.1 and when trying to build my typescript project, your module throw the following errors:

"Namespace '"fs"' has no exported member 'WriteFileOptions'."
"Namespace '"fs"' has no exported member 'MakeDirectoryOptions'."

Module not found: Can't resolve 'fs'

error - ./node_modules/add-filename-increment/index.js:3:0
Module not found: Can't resolve 'fs'

Import trace for requested module:
./node_modules/write/index.js

I get this error when I try to use write. npm says the fs plugin has been removed.

Not working with node 8

When I call the write function and give it a directory that doesn't exist, I get this error.

Error: ENOENT: no such file or directory, open '<project_dir>/<directory_that_doesn't_exist>/<file>'

node version: 8.17.0
write version: 2.0.0

Suggestion

Because node 8 does not support the recursive option (used here) you could use something like sindresorhus/make-dir which only uses the recursive option if the node version is >=10.12.0 (sindresorhus/make-dir/blob/master/index.js#L12).

Unkown encoding "BBB"

In the master branch, the code is using fs.writeFileSync("file.txt", {}, "BBB");, but the node docs says that the signature is fs.writeFileSync("file.txt", "BBB").

Am I missing something?

Using: node v5.7.0.

`increment` doesn't work as expected

Hello!

I've found this issue when tried to use the increment option. In the empty folder I expect the following code to create foo.txt file:

write.sync('foo.txt', 'some data', { increment: true });

But instead it creates foo (2).txt on Windows platform. I dug into the sources and found the fs option in add-filename-increment library. The following code will work correctly:

write.sync('foo.txt', 'some data', {
  increment: true,
  fs: true
});

Possible race condition if 2 calls write to the same file

I think there is a race condition when 2 write() calls write to the same file at almost the same time, like the test case below:

const targetFile = path.join(os.tmpdir(), 'test.txt');

fs.rmSync(targetFile, {force: true});

const content1 = Buffer.alloc(100 * 1024 * 1024); // A will finish writing later than B
const content2 = Buffer.alloc(50 * 1024 * 1024);

crypto.randomFillSync(content1);
crypto.randomFillSync(content2);

process.on('uncaughtException', (e) =>
{
    console.error(e);
});

process.on('beforeExit', () =>
{
    fs.rmSync(targetFile, {force: true});
});

// A
write(targetFile, content1, {overwrite: true}, err =>
{
    if (err)
    {
        console.error(err);
    }
    else
    {
        const targetContent = fs.readFileSync(targetFile);
        assert.ok(targetContent.equals(content1), `The content of targetFile is not content1!`);
    }
});


// B
write(targetFile, content2, {overwrite: true}, err =>
{
    if (err)
    {
        console.error(err);
    }
    else
    {
        const targetContent = fs.readFileSync(targetFile);
        assert.ok(targetContent.equals(content2), `The content of targetFile is not content2!`);
    }
});

And the execution result is:

AssertionError [ERR_ASSERTION]: The content of targetFile is not content2!
...
AssertionError [ERR_ASSERTION]: The content of targetFile is not content1!
...

targetFile may become a corrupted file with content different from either content1 or content2.

I think the bug is caused by the use of stream:

write/index.js

Lines 58 to 61 in f537eb6

fs.createWriteStream(destpath, opts)
.on('error', err => reject(err))
.on('close', resolve)
.end(ensureNewline(data, opts));

Both A and B can create write streams and write to targetFile at the same time. I think write() should check whether a file is being written before writing to it.

Uncaught TypeError: xfs.mkdir is not a function

Uncaught TypeError: xfs.mkdir is not a function index.js?0191:27

I'm using it as per the docs

      writeFile('Report.csv', csv, function(err) {
        if (err) throw err;
      });

csv is a valid object using the json2csv module

Not sure what I'm missing here.
Could be related to #3 ?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.