Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I use fs.createReadstream with fs.promises

I use require("fs").promises just to avoid to use callback function.

But now, I also want to use fs.createReadstream to attach a file with POST request.

How can I do this? Or what alter createReadstream in this case? Or should I use require("fs")?

like image 207
invalid Avatar asked May 10 '19 09:05

invalid


1 Answers

So by using const fs = require('fs').promises; you're only gaining access to the promise version of the fs module. According to spec, there is no equivalent createReadStream entry in the File System Promises API. If you want that functionality, you'll need to store a reference to it in addition to the promisified version of fs.

I'd encourage anyone reading this to use the following at the top of your file to include both the promises api and ability to createReadStreams.

const fs = require('fs').promises;
const createReadStream = require('fs').createReadStream;

Your creation of readstreams will look like this (note no longer includes a prepended fs.):

createReadStream('/your/path/here');

Equally important to note:

According to spec, you'll eventually want to use the following instead (disclaimer, current out of box node can't do this without certain flags/dependences)

import { createReadStream } from 'fs';
like image 69
Arthur Weborg Avatar answered Oct 10 '22 19:10

Arthur Weborg