Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to save filestream as a file in a folder in node

When I upload a file, the server is returning a stream, filename, mimetype, encoding. I can't figure out how to save the stream as a file in my server. I tried fs.createReadStream, I just can't figure out the next steps for it like how do I put it in ./uploads folder?

 { stream:
  FileStream {
    _readableState: [Object],
    readable: true,
    domain: null,
    _events: [Object],
    _eventsCount: 2,
    _maxListeners: undefined,
    truncated: false,
    _read: [Function] },
 filename: 'test-sample.xlsx',
 mimetype: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
 encoding: '7bit' } }
like image 915
Woppi Avatar asked Sep 15 '25 16:09

Woppi


1 Answers

This is the code that worked for me. I'm using Apollo Server and Graphql and 'singleUpload' is the resolver I created for uploading an image.

const path = require("path");
const { createWriteStream } = require("fs");

Both these imports are already included in the node package so you don't need to install them separately.

singleUpload: async (_, { file }) => {
      const { createReadStream, filename, mimetype, encoding } = await file;

      await new Promise((res) =>
        createReadStream()
          .pipe(
            createWriteStream(
              path.join(__dirname, "../../uploads/images", filename)
            )
          )
          .on("close", res)
      );

      return true;
    }
  }
};

The 'file' is the image file I forwarded from <input type="file"/>. The apollo-upload-client in the front-end automatically stores the stream in the 'createReadStream()' that I can destructure form the incoming file promise. I then pipe that stream using 'createWriteStream' and store it in the path I specify on my server. The path within the createWriteStream function is relative to your current directory and the server will look for this folder during runtime, so make sure it exists.

One last thing, if you're serving these images to the front-end directly from the server, make sure to include the line below in your main index.js server file.

app.use("/images", express.static(path.join(__dirname, "./uploads/images")));
like image 185
Sameer Ingavale Avatar answered Sep 17 '25 05:09

Sameer Ingavale