using gridfs-stream write string to gridfs











up vote
1
down vote

favorite












I came acorss snippet to write file to gridfs, but I am unable to find write way to update string to Gridfs.



the below snippet will update using path, but what about direct string buffer?



var metadata = {
"path": path
};
var writestream = gfs.createWriteStream({
filename: name,
mode: 'w',
content_type: type,
metadata: metadata
});
fs.createReadStream(path).pipe(writestream);
// var buf = new Buffer("hello");
writestream.on('close', function (file) {
console.log("Gridfs created");
});









share|improve this question




























    up vote
    1
    down vote

    favorite












    I came acorss snippet to write file to gridfs, but I am unable to find write way to update string to Gridfs.



    the below snippet will update using path, but what about direct string buffer?



    var metadata = {
    "path": path
    };
    var writestream = gfs.createWriteStream({
    filename: name,
    mode: 'w',
    content_type: type,
    metadata: metadata
    });
    fs.createReadStream(path).pipe(writestream);
    // var buf = new Buffer("hello");
    writestream.on('close', function (file) {
    console.log("Gridfs created");
    });









    share|improve this question


























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      I came acorss snippet to write file to gridfs, but I am unable to find write way to update string to Gridfs.



      the below snippet will update using path, but what about direct string buffer?



      var metadata = {
      "path": path
      };
      var writestream = gfs.createWriteStream({
      filename: name,
      mode: 'w',
      content_type: type,
      metadata: metadata
      });
      fs.createReadStream(path).pipe(writestream);
      // var buf = new Buffer("hello");
      writestream.on('close', function (file) {
      console.log("Gridfs created");
      });









      share|improve this question















      I came acorss snippet to write file to gridfs, but I am unable to find write way to update string to Gridfs.



      the below snippet will update using path, but what about direct string buffer?



      var metadata = {
      "path": path
      };
      var writestream = gfs.createWriteStream({
      filename: name,
      mode: 'w',
      content_type: type,
      metadata: metadata
      });
      fs.createReadStream(path).pipe(writestream);
      // var buf = new Buffer("hello");
      writestream.on('close', function (file) {
      console.log("Gridfs created");
      });






      node.js mongodb mongoose gridfs gridfs-stream






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Dec 31 '14 at 19:07









      Disposer

      5,02542237




      5,02542237










      asked Dec 31 '14 at 19:03









      procoder

      166




      166
























          3 Answers
          3






          active

          oldest

          votes

















          up vote
          0
          down vote













          I was faced with the same problem. I just simply deleted the file using gfs.remove and then added the updated file to GridFS.



          Also FYI. I used async.series to finish the delete operation first and then write the updated file to GridFS.



          Hope this helps!






          share|improve this answer




























            up vote
            0
            down vote













            Even though it's been a while. I had this problem and solved it creating a stream from the string instead of a file.
            Like this:



              var writestream = gfs.createWriteStream({
            filename: fileName
            });

            // Create stream with buffer to pipe to writestream
            var s = new stream.Readable();
            s.push(pic);
            s.push(null); // Push null to end stream
            s.pipe(writestream);

            writestream.on('close', function (file) {
            // Do anything with the file
            cb(null, file.filename);
            }).on('error', cb);


            Got the stream idea from here






            share|improve this answer






























              up vote
              0
              down vote













              This page comes up first when searching for how to store a string data in Mongo GridFS using NodeJS. Since most of the answers here and elsewhere are based on deprecated API, I decided to post a code based on a more recent GridFSBucket. The code has an additional provision to overwrite existing files. If you don't need that - you can replace openUploadStreamWithId with openUploadStream which creates duplicates.



              var mongo = require('mongodb');
              var stream = require('stream');
              var MongoClient = mongo.MongoClient;

              function getFileSystemItem(dbo, filename) {
              var buf = new Buffer('');
              return new Promise(function(resolve, reject) {
              var bucket = new mongo.GridFSBucket(dbo);
              var readstream = bucket.openDownloadStream(filename);
              readstream.on('data', (chunk) => {
              buf = Buffer.concat([buf, chunk]);
              });
              readstream.on('error', (err) => {
              reject(err);
              });
              readstream.on('end', () => {
              var res = buf.toString();
              buf = null; // Clean up memory
              readstream.destroy();
              resolve(res);
              });
              });
              }

              function putFileSystemItem(dbo, filename, data) {
              var putItemHelper = function(bucket, resolve, reject) {
              var writeStream = bucket.openUploadStreamWithId(filename, filename);
              var s = new stream.Readable();
              s.push(data);
              s.push(null); // Push null to end stream
              s.pipe(writeStream);
              writeStream.on('finish', resolve);
              writeStream.on('error', reject);
              };
              return new Promise(function(resolve, reject) {
              var bucket = new mongo.GridFSBucket(dbo);
              bucket.find({_id: filename}).count(function(err, count) {
              if (err) return reject(err);
              if (count > 0) {
              bucket.delete(filename, function() {
              putItemHelper(bucket, resolve, reject);
              }, reject)
              } else {
              putItemHelper(bucket, resolve, reject);
              }
              }, reject);
              });
              }

              function test() {
              var MongoUrl = 'mongodb://localhost:27017';
              var dbName = 'test';
              MongoClient.connect(MongoUrl, function(err, db) {
              if (err) throw err;
              var dbo = db.db(DbName);
              putFileSystemItem(dbo, 'test', 'this is a test')
              .then(function(a) {
              console.log('Wrote a gridFS file with metadata:', a);
              return getFileSystemItem(dbo, 'test')
              })
              .then(function(a) {
              console.log('Got data back from a gridFS file:', a);
              db.close();
              })
              .catch(function(e) {
              console.log(e);
              db.close();
              })
              });
              }
              test();


              Credit: This is assembled from a dozen of other StackOverflow pages and MongoDB API help.






              share|improve this answer























                Your Answer






                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "1"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                convertImagesToLinks: true,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: 10,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                 

                draft saved


                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f27725285%2fusing-gridfs-stream-write-string-to-gridfs%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes








                up vote
                0
                down vote













                I was faced with the same problem. I just simply deleted the file using gfs.remove and then added the updated file to GridFS.



                Also FYI. I used async.series to finish the delete operation first and then write the updated file to GridFS.



                Hope this helps!






                share|improve this answer

























                  up vote
                  0
                  down vote













                  I was faced with the same problem. I just simply deleted the file using gfs.remove and then added the updated file to GridFS.



                  Also FYI. I used async.series to finish the delete operation first and then write the updated file to GridFS.



                  Hope this helps!






                  share|improve this answer























                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    I was faced with the same problem. I just simply deleted the file using gfs.remove and then added the updated file to GridFS.



                    Also FYI. I used async.series to finish the delete operation first and then write the updated file to GridFS.



                    Hope this helps!






                    share|improve this answer












                    I was faced with the same problem. I just simply deleted the file using gfs.remove and then added the updated file to GridFS.



                    Also FYI. I used async.series to finish the delete operation first and then write the updated file to GridFS.



                    Hope this helps!







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered May 20 '15 at 0:11









                    user3658423

                    92111639




                    92111639
























                        up vote
                        0
                        down vote













                        Even though it's been a while. I had this problem and solved it creating a stream from the string instead of a file.
                        Like this:



                          var writestream = gfs.createWriteStream({
                        filename: fileName
                        });

                        // Create stream with buffer to pipe to writestream
                        var s = new stream.Readable();
                        s.push(pic);
                        s.push(null); // Push null to end stream
                        s.pipe(writestream);

                        writestream.on('close', function (file) {
                        // Do anything with the file
                        cb(null, file.filename);
                        }).on('error', cb);


                        Got the stream idea from here






                        share|improve this answer



























                          up vote
                          0
                          down vote













                          Even though it's been a while. I had this problem and solved it creating a stream from the string instead of a file.
                          Like this:



                            var writestream = gfs.createWriteStream({
                          filename: fileName
                          });

                          // Create stream with buffer to pipe to writestream
                          var s = new stream.Readable();
                          s.push(pic);
                          s.push(null); // Push null to end stream
                          s.pipe(writestream);

                          writestream.on('close', function (file) {
                          // Do anything with the file
                          cb(null, file.filename);
                          }).on('error', cb);


                          Got the stream idea from here






                          share|improve this answer

























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            Even though it's been a while. I had this problem and solved it creating a stream from the string instead of a file.
                            Like this:



                              var writestream = gfs.createWriteStream({
                            filename: fileName
                            });

                            // Create stream with buffer to pipe to writestream
                            var s = new stream.Readable();
                            s.push(pic);
                            s.push(null); // Push null to end stream
                            s.pipe(writestream);

                            writestream.on('close', function (file) {
                            // Do anything with the file
                            cb(null, file.filename);
                            }).on('error', cb);


                            Got the stream idea from here






                            share|improve this answer














                            Even though it's been a while. I had this problem and solved it creating a stream from the string instead of a file.
                            Like this:



                              var writestream = gfs.createWriteStream({
                            filename: fileName
                            });

                            // Create stream with buffer to pipe to writestream
                            var s = new stream.Readable();
                            s.push(pic);
                            s.push(null); // Push null to end stream
                            s.pipe(writestream);

                            writestream.on('close', function (file) {
                            // Do anything with the file
                            cb(null, file.filename);
                            }).on('error', cb);


                            Got the stream idea from here







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited May 23 '17 at 12:30









                            Community

                            11




                            11










                            answered Jul 28 '15 at 16:08









                            fos.alex

                            1,63231118




                            1,63231118






















                                up vote
                                0
                                down vote













                                This page comes up first when searching for how to store a string data in Mongo GridFS using NodeJS. Since most of the answers here and elsewhere are based on deprecated API, I decided to post a code based on a more recent GridFSBucket. The code has an additional provision to overwrite existing files. If you don't need that - you can replace openUploadStreamWithId with openUploadStream which creates duplicates.



                                var mongo = require('mongodb');
                                var stream = require('stream');
                                var MongoClient = mongo.MongoClient;

                                function getFileSystemItem(dbo, filename) {
                                var buf = new Buffer('');
                                return new Promise(function(resolve, reject) {
                                var bucket = new mongo.GridFSBucket(dbo);
                                var readstream = bucket.openDownloadStream(filename);
                                readstream.on('data', (chunk) => {
                                buf = Buffer.concat([buf, chunk]);
                                });
                                readstream.on('error', (err) => {
                                reject(err);
                                });
                                readstream.on('end', () => {
                                var res = buf.toString();
                                buf = null; // Clean up memory
                                readstream.destroy();
                                resolve(res);
                                });
                                });
                                }

                                function putFileSystemItem(dbo, filename, data) {
                                var putItemHelper = function(bucket, resolve, reject) {
                                var writeStream = bucket.openUploadStreamWithId(filename, filename);
                                var s = new stream.Readable();
                                s.push(data);
                                s.push(null); // Push null to end stream
                                s.pipe(writeStream);
                                writeStream.on('finish', resolve);
                                writeStream.on('error', reject);
                                };
                                return new Promise(function(resolve, reject) {
                                var bucket = new mongo.GridFSBucket(dbo);
                                bucket.find({_id: filename}).count(function(err, count) {
                                if (err) return reject(err);
                                if (count > 0) {
                                bucket.delete(filename, function() {
                                putItemHelper(bucket, resolve, reject);
                                }, reject)
                                } else {
                                putItemHelper(bucket, resolve, reject);
                                }
                                }, reject);
                                });
                                }

                                function test() {
                                var MongoUrl = 'mongodb://localhost:27017';
                                var dbName = 'test';
                                MongoClient.connect(MongoUrl, function(err, db) {
                                if (err) throw err;
                                var dbo = db.db(DbName);
                                putFileSystemItem(dbo, 'test', 'this is a test')
                                .then(function(a) {
                                console.log('Wrote a gridFS file with metadata:', a);
                                return getFileSystemItem(dbo, 'test')
                                })
                                .then(function(a) {
                                console.log('Got data back from a gridFS file:', a);
                                db.close();
                                })
                                .catch(function(e) {
                                console.log(e);
                                db.close();
                                })
                                });
                                }
                                test();


                                Credit: This is assembled from a dozen of other StackOverflow pages and MongoDB API help.






                                share|improve this answer



























                                  up vote
                                  0
                                  down vote













                                  This page comes up first when searching for how to store a string data in Mongo GridFS using NodeJS. Since most of the answers here and elsewhere are based on deprecated API, I decided to post a code based on a more recent GridFSBucket. The code has an additional provision to overwrite existing files. If you don't need that - you can replace openUploadStreamWithId with openUploadStream which creates duplicates.



                                  var mongo = require('mongodb');
                                  var stream = require('stream');
                                  var MongoClient = mongo.MongoClient;

                                  function getFileSystemItem(dbo, filename) {
                                  var buf = new Buffer('');
                                  return new Promise(function(resolve, reject) {
                                  var bucket = new mongo.GridFSBucket(dbo);
                                  var readstream = bucket.openDownloadStream(filename);
                                  readstream.on('data', (chunk) => {
                                  buf = Buffer.concat([buf, chunk]);
                                  });
                                  readstream.on('error', (err) => {
                                  reject(err);
                                  });
                                  readstream.on('end', () => {
                                  var res = buf.toString();
                                  buf = null; // Clean up memory
                                  readstream.destroy();
                                  resolve(res);
                                  });
                                  });
                                  }

                                  function putFileSystemItem(dbo, filename, data) {
                                  var putItemHelper = function(bucket, resolve, reject) {
                                  var writeStream = bucket.openUploadStreamWithId(filename, filename);
                                  var s = new stream.Readable();
                                  s.push(data);
                                  s.push(null); // Push null to end stream
                                  s.pipe(writeStream);
                                  writeStream.on('finish', resolve);
                                  writeStream.on('error', reject);
                                  };
                                  return new Promise(function(resolve, reject) {
                                  var bucket = new mongo.GridFSBucket(dbo);
                                  bucket.find({_id: filename}).count(function(err, count) {
                                  if (err) return reject(err);
                                  if (count > 0) {
                                  bucket.delete(filename, function() {
                                  putItemHelper(bucket, resolve, reject);
                                  }, reject)
                                  } else {
                                  putItemHelper(bucket, resolve, reject);
                                  }
                                  }, reject);
                                  });
                                  }

                                  function test() {
                                  var MongoUrl = 'mongodb://localhost:27017';
                                  var dbName = 'test';
                                  MongoClient.connect(MongoUrl, function(err, db) {
                                  if (err) throw err;
                                  var dbo = db.db(DbName);
                                  putFileSystemItem(dbo, 'test', 'this is a test')
                                  .then(function(a) {
                                  console.log('Wrote a gridFS file with metadata:', a);
                                  return getFileSystemItem(dbo, 'test')
                                  })
                                  .then(function(a) {
                                  console.log('Got data back from a gridFS file:', a);
                                  db.close();
                                  })
                                  .catch(function(e) {
                                  console.log(e);
                                  db.close();
                                  })
                                  });
                                  }
                                  test();


                                  Credit: This is assembled from a dozen of other StackOverflow pages and MongoDB API help.






                                  share|improve this answer

























                                    up vote
                                    0
                                    down vote










                                    up vote
                                    0
                                    down vote









                                    This page comes up first when searching for how to store a string data in Mongo GridFS using NodeJS. Since most of the answers here and elsewhere are based on deprecated API, I decided to post a code based on a more recent GridFSBucket. The code has an additional provision to overwrite existing files. If you don't need that - you can replace openUploadStreamWithId with openUploadStream which creates duplicates.



                                    var mongo = require('mongodb');
                                    var stream = require('stream');
                                    var MongoClient = mongo.MongoClient;

                                    function getFileSystemItem(dbo, filename) {
                                    var buf = new Buffer('');
                                    return new Promise(function(resolve, reject) {
                                    var bucket = new mongo.GridFSBucket(dbo);
                                    var readstream = bucket.openDownloadStream(filename);
                                    readstream.on('data', (chunk) => {
                                    buf = Buffer.concat([buf, chunk]);
                                    });
                                    readstream.on('error', (err) => {
                                    reject(err);
                                    });
                                    readstream.on('end', () => {
                                    var res = buf.toString();
                                    buf = null; // Clean up memory
                                    readstream.destroy();
                                    resolve(res);
                                    });
                                    });
                                    }

                                    function putFileSystemItem(dbo, filename, data) {
                                    var putItemHelper = function(bucket, resolve, reject) {
                                    var writeStream = bucket.openUploadStreamWithId(filename, filename);
                                    var s = new stream.Readable();
                                    s.push(data);
                                    s.push(null); // Push null to end stream
                                    s.pipe(writeStream);
                                    writeStream.on('finish', resolve);
                                    writeStream.on('error', reject);
                                    };
                                    return new Promise(function(resolve, reject) {
                                    var bucket = new mongo.GridFSBucket(dbo);
                                    bucket.find({_id: filename}).count(function(err, count) {
                                    if (err) return reject(err);
                                    if (count > 0) {
                                    bucket.delete(filename, function() {
                                    putItemHelper(bucket, resolve, reject);
                                    }, reject)
                                    } else {
                                    putItemHelper(bucket, resolve, reject);
                                    }
                                    }, reject);
                                    });
                                    }

                                    function test() {
                                    var MongoUrl = 'mongodb://localhost:27017';
                                    var dbName = 'test';
                                    MongoClient.connect(MongoUrl, function(err, db) {
                                    if (err) throw err;
                                    var dbo = db.db(DbName);
                                    putFileSystemItem(dbo, 'test', 'this is a test')
                                    .then(function(a) {
                                    console.log('Wrote a gridFS file with metadata:', a);
                                    return getFileSystemItem(dbo, 'test')
                                    })
                                    .then(function(a) {
                                    console.log('Got data back from a gridFS file:', a);
                                    db.close();
                                    })
                                    .catch(function(e) {
                                    console.log(e);
                                    db.close();
                                    })
                                    });
                                    }
                                    test();


                                    Credit: This is assembled from a dozen of other StackOverflow pages and MongoDB API help.






                                    share|improve this answer














                                    This page comes up first when searching for how to store a string data in Mongo GridFS using NodeJS. Since most of the answers here and elsewhere are based on deprecated API, I decided to post a code based on a more recent GridFSBucket. The code has an additional provision to overwrite existing files. If you don't need that - you can replace openUploadStreamWithId with openUploadStream which creates duplicates.



                                    var mongo = require('mongodb');
                                    var stream = require('stream');
                                    var MongoClient = mongo.MongoClient;

                                    function getFileSystemItem(dbo, filename) {
                                    var buf = new Buffer('');
                                    return new Promise(function(resolve, reject) {
                                    var bucket = new mongo.GridFSBucket(dbo);
                                    var readstream = bucket.openDownloadStream(filename);
                                    readstream.on('data', (chunk) => {
                                    buf = Buffer.concat([buf, chunk]);
                                    });
                                    readstream.on('error', (err) => {
                                    reject(err);
                                    });
                                    readstream.on('end', () => {
                                    var res = buf.toString();
                                    buf = null; // Clean up memory
                                    readstream.destroy();
                                    resolve(res);
                                    });
                                    });
                                    }

                                    function putFileSystemItem(dbo, filename, data) {
                                    var putItemHelper = function(bucket, resolve, reject) {
                                    var writeStream = bucket.openUploadStreamWithId(filename, filename);
                                    var s = new stream.Readable();
                                    s.push(data);
                                    s.push(null); // Push null to end stream
                                    s.pipe(writeStream);
                                    writeStream.on('finish', resolve);
                                    writeStream.on('error', reject);
                                    };
                                    return new Promise(function(resolve, reject) {
                                    var bucket = new mongo.GridFSBucket(dbo);
                                    bucket.find({_id: filename}).count(function(err, count) {
                                    if (err) return reject(err);
                                    if (count > 0) {
                                    bucket.delete(filename, function() {
                                    putItemHelper(bucket, resolve, reject);
                                    }, reject)
                                    } else {
                                    putItemHelper(bucket, resolve, reject);
                                    }
                                    }, reject);
                                    });
                                    }

                                    function test() {
                                    var MongoUrl = 'mongodb://localhost:27017';
                                    var dbName = 'test';
                                    MongoClient.connect(MongoUrl, function(err, db) {
                                    if (err) throw err;
                                    var dbo = db.db(DbName);
                                    putFileSystemItem(dbo, 'test', 'this is a test')
                                    .then(function(a) {
                                    console.log('Wrote a gridFS file with metadata:', a);
                                    return getFileSystemItem(dbo, 'test')
                                    })
                                    .then(function(a) {
                                    console.log('Got data back from a gridFS file:', a);
                                    db.close();
                                    })
                                    .catch(function(e) {
                                    console.log(e);
                                    db.close();
                                    })
                                    });
                                    }
                                    test();


                                    Credit: This is assembled from a dozen of other StackOverflow pages and MongoDB API help.







                                    share|improve this answer














                                    share|improve this answer



                                    share|improve this answer








                                    edited Nov 8 at 19:35

























                                    answered Nov 8 at 16:49









                                    Maksym

                                    660510




                                    660510






























                                         

                                        draft saved


                                        draft discarded



















































                                         


                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f27725285%2fusing-gridfs-stream-write-string-to-gridfs%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Schultheiß

                                        Liste der Kulturdenkmale in Wilsdruff

                                        Android Play Services Check