Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pipe to a file (NodeJS)

I have created some image data which I've obtained from pixels. Anyway, now I would like to write a file using save-pixels, but the docs only give

var savePixels = require("save-pixels")
...
savePixels(pixels, "png").pipe(process.stdout)

How to rewrite this such that it writes it to a file with a specific name ?

like image 850
Jeanluca Scaljeri Avatar asked Mar 01 '16 17:03

Jeanluca Scaljeri


People also ask

How do I pipe data in node JS?

pipe() Method. The readable. pipe() method in a Readable Stream is used to attach a Writable stream to the readable stream so that it consequently switches into flowing mode and then pushes all the data that it has to the attached Writable.

What is .pipe in node JS?

pipe was added in v0. 9.4 of Node. js and its purpose is to attach a writeable stream to a readable stream allowing to pass the readable stream data to the writeable stream.

What is file stream Nodejs?

Filestream in Node. js. Node makes extensive use of streams as a data transfer mechanism. For example, when you output anything to the console using the console. log function, you are actually using a stream to send the data to the console.

How do you write to a file in Javascript?

Import fs-module in the program and use functions to write text to files in the system. The following function will create a new file with a given name if there isn't one, else it will rewrite the file erasing all the previous data in it. Used Function: The writeFile() functions is used for writing operation.


1 Answers

Use the file system module included with node. Something like this:

var fs = require("fs");
var savePixels = require("save-pixels");
var myFile = fs.createWriteStream("myOutput.txt");
...
savePixels(pixels, "png").pipe(myFile);
like image 163
rgvassar Avatar answered Oct 19 '22 15:10

rgvassar