• Stars
    star
    117
  • Rank 301,828 (Top 6 %)
  • Language
    JavaScript
  • License
    Other
  • Created over 10 years ago
  • Updated about 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Now stdin and stdout are files.

rw - Now stdin and stdout are files.

How do you read a file from stdin? If you thought,

var contents = fs.readFileSync("/dev/stdin", "utf8");

you’d be wrong, because Node only reads up to the size of the file reported by fs.stat rather than reading until it receives an EOF. So, if you redirect a file to your program (cat file | program), you’ll only read the first 65,536 bytes of your file. Oops.

What about writing a file to stdout? If you thought,

fs.writeFileSync("/dev/stdout", contents, "utf8");

you’d also be wrong, because this tries to close stdout, so you get this error:

Error: UNKNOWN, unknown error
    at Object.fs.writeSync (fs.js:528:18)
    at Object.fs.writeFileSync (fs.js:975:21)

(Also, this doesn’t work on Windows, because Windows doesn’t support /dev/stdout, /dev/stdin and /dev/stderr!)

Shucks. So what should you do?

You could use a different pattern for reading from stdin:

var chunks = [];

process.stdin
    .on("data", function(chunk) { chunks.push(chunk); })
    .on("end", function() { console.log(chunks.join("").length); })
    .setEncoding("utf8");

But that’s a pain, since now your code has two different code paths for reading inputs depending on whether you’re reading a real file or stdin. And the code gets even more complex if you want to read that file synchronously.

You could also try a different pattern for writing to stdout:

process.stdout.write(contents);

Or even:

console.log(contents);

But if you try to pipe your output to head, you’ll get this error:

Error: write EPIPE
    at errnoException (net.js:904:11)
    at Object.afterWrite (net.js:720:19)

Huh.

The rw module fixes these problems. It provides an interface just like readFile, readFileSync, writeFile and writeFileSync, but with implementations that work the way you expect on stdin and stdout. If you use these methods on files other than /dev/stdin or /dev/stdout, they simply delegate to the fs methods, so you can trust that they behave identically to the methods you’re used to.

For example, now you can read stdin synchronously like so:

var contents = rw.readFileSync("/dev/stdin", "utf8");

Or to write to stdout:

rw.writeFileSync("/dev/stdout", contents, "utf8");

And rw automatically squashes EPIPE errors, so you can pipe the output of your program to head and you won’t get a spurious stack trace.

To install, npm install rw.

Note

If you want to read synchronously from stdin using readFileSync, you cannot also use process.stdin in the same program. Likewise, if you want to write synchronously to stdout or stderr using writeFileSync, you cannot use process.stdout or process.stderr, respectively. (This includes using console.log and the like!) Failure to heed this warning may result in error: EAGAIN, resource temporarily unavailable. Unfortunately, it does not appear possible for this library to fix this issue automatically, so please use caution.

Only the asynchronous methods readFile and writeFile are supported on Windows. Node has no synchronous API for reading from process.stdin or writing to process.stdout or process.stderr, so you’re out of luck!

API Reference

# rw.readFile(path[, options], callback)

Reads the file at the specified path completely into memory, invoking the specified callback once the data is available and the file is closed. The callback is invoked with two arguments: the error that occurred during read (hopefully null), and the read data. If options is a string, it specifies the encoding to use, in which case the read data will be a string; otherwise options is an object, and may specify encoding and flag properties. This method is a drop-in replacement for fs.readFile and fixes the behavior of special files such as /dev/stdin.

# rw.readFileSync(path[, options])

Reads the file at the specified path completely into memory, synchronously, returning the data. If an error occurred during read, this function throws an error instead. If options is a string, it specifies the encoding to use, in which case the read data will be a string; otherwise options is an object, and may specify encoding and flag properties. This method is a drop-in replacement for fs.readFileSync and fixes the behavior of special files such as /dev/stdin.

# rw.writeFile(path, data[, options], callback)

Writes the specified data (completely in memory) to a file at the specified path, invoking the specified callback once the data is completely written and the file is closed. The callback is invoked with a single argument: the error that occurred during write (hopefully null). If options is a string, it specifies the encoding to use, in which case the data must be a string; otherwise options is an object, and may specify encoding, mode and flag properties. This method is a drop-in replacement for fs.writeFile and fixes the behavior of special files such as /dev/stdout.

# rw.writeFileSync(path, data[, options])

Writes the specified data (completely in memory) to a file at the specified path, synchronously, returning once the data is completely written and the file is closed. Throws an error if one occurs during write. If options is a string, it specifies the encoding to use, in which case the data must be a string; otherwise options is an object, and may specify encoding, mode and flag properties. This method is a drop-in replacement for fs.writeFileSync and fixes the behavior of special files such as /dev/stdout.

# rw.dash.readFile(path[, options], callback)

Equivalent to rw.readFile, except treats a path of - as /dev/stdin. Useful for command-line arguments.

# rw.dash.readFileSync(path[, options])

Equivalent to rw.readFileSync, except treats a path of - as /dev/stdin. Useful for command-line arguments.

# rw.dash.writeFile(path, data[, options], callback)

Equivalent to rw.writeFile, except treats a path of - as /dev/stdout. Useful for command-line arguments.

# rw.dash.writeFileSync(path, data[, options])

Equivalent to rw.writeFileSync, except treats a path of - as /dev/stdout. Useful for command-line arguments.

More Repositories

1

stack

A presentation library with intuitive, scroll-based navigation.
JavaScript
1,155
star
2

shapefile

A cross-platform streaming parser for the ESRI Shapefile spatial data format.
JavaScript
754
star
3

protovis

A visualization toolkit for JavaScript using SVG.
JavaScript
625
star
4

gistup

Create a gist from terminal, then use git to update it.
JavaScript
490
star
5

ndjson-cli

Command line tools for operating on newline-delimited JSON streams.
JavaScript
272
star
6

smash

SMASH TOGETHER MULTIPLE FILES [deprecated; try rollup/rollup]
JavaScript
199
star
7

solar-calculator

Equations for computing the position of the Sun.
JavaScript
140
star
8

us-rivers

A map of flowlines from NHDPlus.
JavaScript
123
star
9

git-static

A versioned static file server backed by Git.
JavaScript
116
star
10

bl.ocks.org

Browser Extensions for bl.ocks.org
JavaScript
92
star
11

svjimmy

A bookmarklet to download SVG as PNG.
HTML
74
star
12

polly-b-gone

A physics platform game about a plucky wheeled robot named Polly.
C++
61
star
13

pixymaps

Experimental canvas-based mapping library.
JavaScript
57
star
14

json-write

A stream-based serializer for JSON.
JavaScript
36
star
15

internmap

Map and Set with automatic key interning
JavaScript
32
star
16

dependency-tree

Hierarchical edge bundling in JavaScript & Canvas.
JavaScript
31
star
17

topoedit

A visual editor for TopoJSON.
28
star
18

isoformat

Formats dates as the shortest equivalent ISO 8601 UTC string
JavaScript
25
star
19

node-mappy

Server-side map rendering for Node.
JavaScript
24
star
20

file-source

Read files as standard WhatWG streams in Node.
JavaScript
22
star
21

epheme

The precursor to D3.
JavaScript
21
star
22

path-data

An SVG path parser and normalizer.
JavaScript
19
star
23

mbostock.github.com

Redirect to http://bost.ocks.org/mike/.
19
star
24

json2module

Convert a JSON object to an ES6 module.
JavaScript
18
star
25

cube-logplex

Route Heroku logs to Cube for analysis and visualization.
JavaScript
17
star
26

tape-await

Yet another async-await helper for tape.
JavaScript
17
star
27

colorbrewer-theme

ColorBrewer-based themes for Sublime Text.
16
star
28

mongo-mock

DEPRECATED
JavaScript
16
star
29

topotree

Spatial indexing for topological operations.
JavaScript
15
star
30

preamble

Generate a tiny preamble from a package.json.
JavaScript
14
star
31

rollup-plugin-ascii

Rewrite JavaScript to escape any non-ASCII characters in string literals.
JavaScript
12
star
32

dedom

A partial implementation of the W3C DOM API on top of an HTML5 parser and serializer.
JavaScript
12
star
33

stream-source

Read Node streams as standard WhatWG streams.
JavaScript
12
star
34

twitch-chat-relay

A relay to allow listening to Twitch chat.
JavaScript
11
star
35

slice-source

Read the specified number of bytes from a standard WhatWG stream.
JavaScript
10
star
36

nns

DEPRECATED; Use D3.
JavaScript
9
star
37

cstree

Comma-separated tree
JavaScript
8
star
38

hide-google-plus-notification

Extensions for hiding the annoying red Google+ notification.
CSS
7
star
39

randomized-flood-fill

Flood fill with color randomization.
JavaScript
7
star
40

por

A streaming parser for the Portable File Format (.por) used by PSPP & SPSS.
JavaScript
7
star
41

array-source

Read arrays as standard WhatWG streams.
JavaScript
6
star
42

justascii

Rewrite JavaScript to escape any non-ASCII characters in string literals.
JavaScript
6
star
43

path-source

Read files in Node, or fetch URLs in browser, as standard WhatWG streams.
JavaScript
5
star
44

rw-vs-fs

Comparing rw with Node’s built-in fs & stream.
JavaScript
5
star
45

relative-time-format-locale

An AMD-friendly distribution of relative-time-format and its locales.
JavaScript
4
star
46

hide-flickr-eyebrow

Hide that ghastly eyebrow.
JavaScript
3
star
47

ocks.org

http://ocks.org
3
star
48

rollup-1655

A test case for rollup/rollup#1655.
JavaScript
2
star
49

crom-test-foo

A simple test for Crom dependencies.
JavaScript
2
star
50

rollup-leaflet-example

Using Rollup to bundle Leaflet and plugins as an ES module.
JavaScript
2
star
51

crom-test-bar

Another test for Crom dependencies.
2
star
52

framework-help

Examples and answers to support questions for Observable Framework
JavaScript
2
star
53

node-envy

DEPRECATED; Use env-js, jsdom, etc.
JavaScript
1
star