Read file with node.js, mongoose, gridfs-stream

前端 未结 2 1332
孤街浪徒
孤街浪徒 2021-02-09 22:49

I am using mongoose and gridfs-stream to store and read files from mongodb. I am following the example here: https://github.com/aheckmann/gridfs-stream

Writing files int

相关标签:
2条回答
  • 2021-02-09 23:25

    what is cover give an format to file than write or read

    const express = require("express");
    const routes = express.Router();
    const mongoose = require('mongoose');
    mongoose.connect("mongodb://localhost:27017/gridfs");
    var conn = mongoose.connection;
    var path = require("path");
    var Grid = require("gridfs-stream");
    var fs = require("fs");
    Grid.mongo = mongoose.mongo;
    
    var datapath = path.join(__dirname, "../public/1.jpg");
    
    conn.once("open",() =>{
        console.log('connections is opened ');
        console.log(conn.db + "wahab this is running");
        var gfs = Grid(conn.db);
        var filestream = gfs.createWriteStream({
          filename: "wahab.jpg"
        });
        fs.createReadStream(datapath).pipe(filestream);
        filestream.on("close",(file) =>{
          console.log(file.filename  + " Write to DB");
        });
    
     });
    
     });
    
    0 讨论(0)
  • 2021-02-09 23:50

    The example code on GitHub was a little bit misleading; I initially received the same error message you did. In my case, it was due to the fact that I was attempting to read the file before the write stream had finished. I resolved this by doing the read inside the event handler for "close":

    var fs = require("fs"),
        mongo = require("mongodb"),
        Grid = require("gridfs-stream"),
        gridfs,
        writeStream,
        readStream,
        buffer = "";
    
    mongo.MongoClient.connect("mongodb://localhost/gridfs_test", function (err, db) {
        "use strict";
        gridfs = Grid(db, mongo);
    
        // write file
        writeStream = gridfs.createWriteStream({ filename: "test.txt" });
        fs.createReadStream("test.txt").pipe(writeStream);
    
        // after the write is finished
        writeStream.on("close", function () {
            // read file, buffering data as we go
            readStream = gridfs.createReadStream({ filename: "test.txt" });
    
            readStream.on("data", function (chunk) {
                buffer += chunk;
            });
    
            // dump contents to console when complete
            readStream.on("end", function () {
                console.log("contents of file:\n\n", buffer);
            });
        });
    });
    
    0 讨论(0)
提交回复
热议问题