How to use the createWriteStream function from fs-extra

Find comprehensive JavaScript fs-extra.createWriteStream code examples handpicked from public code repositorys.

fs-extra.createWriteStream is a method in the fs-extra library that creates a writable stream for a given file path.

466
467
468
469
470
471
472
473
474
475
476
function downloadFile(url, filePath) {
    // Promisify the request
    return new Promise(function (resolve, reject) {
        try {
            // Create write stream
            var stream = fs.createWriteStream(filePath);


            // Wait for finish event
            stream.on('finish', function () {
                // Resolve the promise
fork icon86
star icon477
watch icon0

135
136
137
138
139
140
141
142
143
144
    return;
}

Fs.ensureDirSync(server.buildPath(meta.path));

var file = Fs.createWriteStream(server.buildPath(Path.join(meta.path, meta.name)));
stream.pipe(file);

stream.on('data', function (data) {
    stream.write({rx: data.length / meta.size});
fork icon11
star icon17
watch icon0

How does fs-extra.createWriteStream work?

fs-extra.createWriteStream is a method in the fs-extra library that creates a writable stream for a given file path. When you call fs.createWriteStream(path, options), the function returns a writable stream that can be used to write data to the file specified by path. The options parameter is an object that can be used to specify additional options for the stream, such as the encoding to use for the data. You can write data to the stream using the .write() method and close the stream using the .end() method. Data written to the stream is buffered until the buffer size exceeds the high water mark specified in the stream options, at which point the data is written to the file. In essence, fs-extra.createWriteStream provides a way to create a writable stream to a file, allowing you to write data to the file incrementally rather than all at once. This can be useful for writing large amounts of data to a file without having to load it all into memory at once.

40
41
42
43
44
45
46
47
48
49
50
toolUtils.downloadFile = function(url, targetPath) {
	const https = require('https');
	const fs = require('fs');


	return new Promise((resolve, reject) => {
		const file = fs.createWriteStream(targetPath);
		https.get(url, function(response) {
			if (response.statusCode !== 200) reject(new Error(`HTTP error ${response.statusCode}`));
			response.pipe(file);
			file.on('finish', function() {
fork icon8
star icon43
watch icon13

+ 8 other calls in file

333
334
335
336
337
338
339
340
341
if (dataset.isRest) return restDatasetsUtils.writeExtendedStreams(db, dataset)
const tmpFullFile = await tmp.tmpName({ dir: path.join(dataDir, 'tmp') })
// creating empty file before streaming seems to fix some weird bugs with NFS
await fs.ensureFile(tmpFullFile)

const writeStream = fs.createWriteStream(tmpFullFile)

const relevantSchema = dataset.schema.filter(f => !f['x-calculated'])
const transforms = []
fork icon6
star icon26
watch icon4

Ai Example

1
2
3
4
5
6
7
8
9
const fs = require("fs-extra");

const writeStream = fs.createWriteStream("./output.txt");

writeStream.write("Hello, world!");
writeStream.write("This is a test.");
writeStream.end();

console.log("Data written to file.");

In this example, we first import the fs-extra library. We then call fs.createWriteStream('./output.txt') to create a writable stream to the file output.txt. The function returns a WriteStream object that we can use to write data to the file. We then write two strings to the stream using the .write() method, and close the stream using the .end() method. Finally, we log a message to the console indicating that the data has been written to the file. Note that in this example, we're writing two small strings to the file, but you can write any type of data to the stream, such as binary data or large data sets.

228
229
230
231
232
233
234
235
236
237
- fs.chmod():更改通过传递的文件名指定的文件的权限。相关阅读:fs.lchmod(),fs.fchmod()
- fs.chown():更改由传递的文件名指定的文件的所有者和组。相关阅读:fs.fchown(),fs.lchown()
- fs.close():关闭文件描述符
- fs.copyFile():复制文件
- fs.createReadStream():创建可读的文件流
- fs.createWriteStream():创建可写文件流
- fs.link():创建指向文件的新硬链接
- fs.mkdir(): 新建一个文件夹
- fs.mkdtemp():创建一个临时目录
- fs.open():设置文件模式
fork icon0
star icon12
watch icon1

+ 27 other calls in file

40
41
42
43
44
45
46
47
48
49

const file_dest = path.join(dest, entry.fileName);
const dest_dir = path.parse(file_dest).dir;
if (!fs.existsSync(dest_dir)) fs.mkdirsSync(dest_dir);

const write_stream = fs.createWriteStream(file_dest);
readStream.pipe(write_stream);
write_stream.on('finish', function() {
  if (stat.mode === 33261) exec(`chmod +x "${file_dest}"`);
  return resolve();
fork icon169
star icon0
watch icon2

+ 3 other calls in file

42
43
44
45
46
47
48
49
50
51
this.emit('start')

fs.ensureDirSync( path.dirname(this.output) )

const rs = fs.createReadStream(this.input)
const ws = fs.createWriteStream(this.output)

rs.on('data', ( chunk ) => {
  chunk = Buffer.isBuffer(chunk) ? chunk.toString('utf8') : chunk
  ws.write( this.renderSource(chunk) )
fork icon1
star icon4
watch icon0

88
89
90
91
92
93
94
95
96
97

// Download file from discord to a local file path
try {
  var response = await fetch(discordFileUrl);
  var readStream = response.body;
  var writeSteam = fs.createWriteStream(downloadFilePath);
  await asyncPipe(readStream, writeSteam);
  //await readStream.pipe(fs.createWriteStream(downloadFilePath));
} catch (err) {
  return reject({
fork icon1
star icon1
watch icon2

+ 11 other calls in file

1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
    };
    const readStream =
        fs.createReadStream(stdcellPath);
    readStream.on("error", done);
    const writeStream =
        fs.createWriteStream(stdCellDest);
    writeStream.on("error", done);
    writeStream.on("close", done);
    return readStream.pipe(writeStream);
}
fork icon0
star icon2
watch icon3

+ 9 other calls in file

1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
    // Adjust download
    this.totaldlsize -= asset.size
    this.totaldlsize += contentLength
}

let writeStream = fs.createWriteStream(asset.to)
writeStream.on('close', () => {
    if(dlTracker.callback != null){
        dlTracker.callback.apply(dlTracker, [asset, self])
    }
fork icon0
star icon1
watch icon0

+ 6 other calls in file

91
92
93
94
95
96
97
98
99
100
if (stripKeyPath) file = basename(file);
const destination = join(path, file);

await fs.ensureDir(dirname(destination));

const writer = fs.createWriteStream(destination);

const { Body } = await s3.getObject({ Bucket, Key });

Body.pipe(writer);
fork icon0
star icon1
watch icon1

7267
7268
7269
7270
7271
7272
7273
7274
7275
  })
}

function copyFile (file, target) {
  var readStream = fs.createReadStream(file.name)
  var writeStream = fs.createWriteStream(target, { mode: file.mode })

  readStream.on('error', onError)
  writeStream.on('error', onError)
fork icon0
star icon1
watch icon0

+ 17 other calls in file

181
182
183
184
185
186
187
188
189
190
191
}


async function _writeToDisk() {
  const streamWrite = async (fpath, data) => {
    await fs.ensureDir(path.dirname(fpath))
    const writeStream = fs.createWriteStream(fpath)
    await writeStream.write(data)
    writeStream.end()
  }

fork icon0
star icon1
watch icon0

247
248
249
250
251
252
253
254
255
256
  return fs.outputFile(join(uploadDir, "error.txt"), err.message);
}

// zip the image and send it
let archive = archiver("zip");
const resultWS = fs.createWriteStream(resultZip);

archive.on("end", () => {
  console.log(archive.pointer() + " total bytes");
  console.log("archiver finalized");
fork icon69
star icon0
watch icon23

+ 4 other calls in file

139
140
141
142
143
144
145
146
147
148
tmp_name = uuid() + basename(req.baseUrl + req.path);
tmp_path = join(tmp_directory, tmp_name);

// Initiate the stream to the location we'll
// write the response to this request.
stream = fs.createWriteStream(tmp_path);

// I suspect this catches an error which results when you flush the
// cache for a given site, whilst caching the response to a request to
// a page on the site. Allow a sudden, the file to which the stream
fork icon69
star icon0
watch icon23

+ 7 other calls in file

116
117
118
119
120
121
122
123
124
125
fs.ensureDirSync(diffDirNegative); // Make sure destination folder exists, if not, create it

if (error > this.expected) {
  diffFile = `${diffDirNegative}${filename}`;

  const writeStream = fs.createWriteStream(diffFile);
  await result.getDiffImage().pack().pipe(writeStream);
  writeStream.on('error', (err) => {
    console.log('this is the writeStream error ', err);
  });
fork icon29
star icon40
watch icon4

478
479
480
481
482
483
484
485
486
487
		fs.rmSync(modlocation);
	}
}

// write out the file to the temporary location
let stream = fs.createWriteStream(modlocation);
res.pipe(stream);

stream.on("finish", () => {
	stream.close();
fork icon17
star icon106
watch icon4

+ 17 other calls in file

17
18
19
20
21
22
23
24
25
26
27
 * @private
 */
function copyFileContent(source, output, transforms) {
    return new Promise((resolve, reject) => {
        const reader = fs.createReadStream(source)
        const writer = fs.createWriteStream(output)
        const streams = [reader]


        /**
         * Clean up.
fork icon3
star icon27
watch icon2

+ 8 other calls in file

43
44
45
46
47
48
49
50
51
52
  "attachment; filename=",
  ""
);

var destf = path.join("upgrade-nobejs", filename);
var dest = fs.createWriteStream(destf);

var total = parseInt(res2.headers["content-length"]);
// console.log("total", total);
var completed = 0;
fork icon1
star icon0
watch icon1

+ 11 other calls in file

26
27
28
29
30
31
32
33
34
35
// https://stackoverflow.com/questions/18814221/adding-timestamps-to-all-console-messages
// https://github.com/iccicci/rotating-file-stream#readme
const logToFile = (process.argv.length > 4);
if (logToFile) { // all output to stdout?
  const logfileName = (process.argv.length > 4) ? process.argv[4] : `/opt/locus/var/log/${appName}.log`;
  const logFile = fs.createWriteStream(logfileName, { flags: 'as' });
  process.stdout.write = process.stderr.write = logFile.write.bind(logFile);
  console.error(`${appName} stderr log to file use env.SET DEBUG_COLORS=NO`);
}
// console.error(`${appName} stderr log to file`, tty.isatty(process.stderr.fd));
fork icon0
star icon0
watch icon1

function icon

fs-extra.readFileSync is the most popular function in fs-extra (9724 examples)