How to create database within nodejs application code in node-webkit? - node.js

I'm trying to use NeDB database for persistence of application data. I'm trying to use the following approach to connect to my database like the following:
var Datastore = require('nedb')
, path = require('path')
, db = new Datastore({ filename: path.join(require('nw.gui').App.dataPath, 'something.db') }
But unfortunatly it fails because this works only client code withit <script></script> tags in html file. How could I do same thing on server side?

The problem here is, that you cannot require('nw.gui') in the nodejs context, because in the nodejs environment is no window. No window, no gui. So what you can do, is just create a script tag in your main file (index.html) with the src to your db.js file with the above content, it should work fine.
in index.html
<script src="db/db.js"></script>
in db/db.js
var Datastore = require('nedb')
, path = require('path')
, dbFile = path.join(require('nw.gui').App.dataPath, 'something.db')
, db = new Datastore({ filename: dbFile })

Related

Dynamically connect to NodeJS server using socket.io

I have an ionic chatting app and a nodejs server , it works fine , the only issue that is the server ip/port is hardcoded in a config object.
let config = { url:"192.168.1.4:3000" , opt: ""}
But I would like to change this approach, and fetch the server ip/port dynamically or from a file ?
You can create a config.js file and put your things there
Config.js:
{
url:"192.168.1.4:3000"
}
And import the file:
var cnfg = require('./config');
let config = { url:cnfg.url , opt: ""}

Node.js reads the file but does not write JSON in the HTML

I'm currently running Node.js by Browserify for my website.
It reads the JSON file and I get the message through MQTT.
But the problem is that it seems like writefile does not work.
(Running this as node test.js in the terminal works by the way).
What is wrong with my code?
Moreover, Is this the best way to store any user data?
Thank you so much in advance.
Here's some part of my code
var fs = require("fs");
var path = require("path");
let newFile = fs.readFileSync('/home/capstone/www/html/javascript/test.json');
function testT() { //THIS WORKS FINE
let student0 = JSON.parse(newFile);
var myJSON = JSON.stringify(student0);
client.publish("send2IR", myJSON);
response.end();
};
function write2JSON() { //PROBLEM OF THIS CODE
const content = 'Some content!'
fs.writeFileSync('/home/capstone/www/html/javascript/test.json', content)
};
document.getElementById("blink").addEventListener("click", publish);
document.getElementById("write").addEventListener("click", write2JSON);
You cann't write directly for security reasons. For other hand you can use a server as API to do the filye system tasks and in the client only trigger the events.
This post is very related with your problem:
Is it possible to write data to file using only JavaScript?

How can I read the mp3 files from the mongodb that I have stored using gridFS?

My code:
storeAudio.js
var mongoose = require('mongoose');
var fs = require('fs');
var Grid = require('gridfs-stream');
Grid.mongo=mongoose.mongo;
//establish mongoDB connection
mongoose.Promise = global.Promise;
var conn = mongoose.createConnection('mongodb://localhost:27017/aHolyBoly');
conn.once('open',function(){
var gfs = Grid(conn.db);
// var db = new mongo.Db('aHolyBoly', new mongo.Server("127.0.0.1", 27017));
//var gfs = Grid(db, mongo);
var writeStream = gfs.createWriteStream({
filename:'song1.mp3'
});
fs.createReadStream('../list/hero.mp3').pipe(writeStream);
writeStream.on('close',function(file){
console.log(file.filename +'Written to db');
});
});
my mp3 file is written successfully in the DB.
Now my aim is to create the routes using express so that I can use it as an API using as providers in my angular2 app.
server.js
var mongoose = require('mongoose');
var fs = require('fs');
var Grid = require('gridfs-stream');
Grid.mongo=mongoose.mongo;
//establish mongoDB connection
mongoose.Promise = global.Promise;
var conn = mongoose.createConnection('mongodb://localhost:27017/aHolyBoly');
conn.once('open',function(){
var gfs = Grid(conn.db);
// var db = new mongo.Db('aHolyBoly', new mongo.Server("127.0.0.1", 27017));
//var gfs = Grid(db, mongo);
var writeStream = gfs.createWriteStream({
filename:'song1.mp3'
});
fs.createReadStream('../list/hero.mp3').pipe(writeStream);
writeStream.on('close',function(file){
console.log(file.filename +'Written to db');
});
});
Here somewhere in my code, I am unable to find the song written in the Db using gridFS.
link for gridFS API gridFS API Link
I want to create an application using ionic2 which contains a search bar and when I enter song name it will display the songs and I can play it.
I am struggling from 1 week written this 3 times on stack but unable to get the answer.
I bet you are a newbie in server-side web development, because your question kinda misses the whole point of creating a node.js application.
When writing a server the goal is that the server cannot access the files on the client's computer. This means your app acts as a thin client. Don't confuse that node.js runs on your computer as well: it creates his own mock server which acts as a real faraway computer even though it is on your very same computer that you use. For this reason you cannot modify files outside of your project library, or even if you can it will be a hack and it is not what node.js is made for.
If you want a program specifically to modify files on your computer you should learn a thick client programming language, like C, C++ or Java. They only run on your computer ad have full access to any of your files.
If you are sticking to JavaScript for whatever reason, it as well has the power to modify your files, however it is still not what it is intended for. You have to give it special permissions and it still is weird that you give access to all your personal files to your browser. However this Javascript code id on the client side i.e. you don't need node.js, neither express. The client code can be written and run with a single browser. Check out this article for more information about it.
But if you are still convinced that node is your way, then you have some options still. First, but I don't think it is your answer: write an upload website which uploads the mp3 files to your server (still on the same computer but places it in the project location). It should work and look like an actual website (like what node.js was made for). And finally what you're asking for can be kinda achieved, but it's reaaaaally hacky, you can try and just reference it from the application path like
var fs = require('fs'),
path = require('path'),
filePath = path.join(__dirname, '../outerfile.mp3')
filePath2 = path.join('/var/outerfile.mp3');
However it is probably platform dependent how it will run and not likely to be working at all.
My final advice: you should consider using another language for your project.

Passing objects between nodejs and jade

I have the following code in my server.js
var cddata = [];
body.rows.forEach(function(doc) {
cddata.push([{id: doc.id, name: doc.key, text:doc.value.Time, group: 1}]);
});
response.render('timeline', {cddata: JSON.stringify(cddata)});
and I have the following in my Jade view file
script(src='vis/dist/vis.js')
link(rel="stylesheet", href="vis/dist/vis.css", type="text/css")
script.
//alert(cddata);
var options = {};
var data = new vis.DataSet(cddata);
var container = document.getElementById('visualization');
new vis.Timeline(container, data, options);
However, nothing related to the chart is rendered. I presume the object is not correctly passed to the jade file. Please help!
Also, is there a way to verify the incoming object in Jade? Alerts dont seem to work.
thanks
The <script> in your jade is a browser side script so won't be able to access variables in the templates generation scope. You'll need to output your data as JSON and read it in using browser side JavaScript, something like this:
script(src='vis/dist/vis.js')
link(rel="stylesheet", href="vis/dist/vis.css", type="text/css")
script.
var chartData = JSON.parse('#{cddata}')
var options = {};
var data = new vis.DataSet(chartData);
var container = document.getElementById('visualization');
new vis.Timeline(container, data, options);
After much deliberation, the following worked to pass object from node server to client side server scripting on Jade file.
on the server.js, where dbdata is an array of JSON objects
response.render('timeline', {dbdata:dbdata});
On the jade file,
script.
var chartData = !{JSON.stringify(dbdata)};
Thanks,

Sync a PouchDB on Nodejs server (without Pochdb-server or Couch)

I want to Sync() the PouchDb on my Nodejs-server with the IndexedDb at frontend.
But : I dont use Couch or Pouchdb-server
on Backend I'm runnig :
var pouch = require('pouchdb')
var db = new pouch('fuu');
test.app.use('/sync'),function(req,res,next){console.log('Woop woop');
db.info(function)(err,info) {return res.send('info')})
});
// same problem with : db.allDocs(..);
on frontend:
var db = new PouchDB('ba');
var remoteCouch = ("http://localhost:3000/sync")
var sync = function() {
var opts = {live: true};
db.sync(remoteCouch, opts);}
sync();
But now there is an endless call of 'Woob woob' in the console and nothing sync's ..
Have someone an idea what I'm doing wrong?
You need to correctly map all the urls that PouchDB will use to be able to sync. I aassume your backend is a typo and you are using var db = new PouchDB('fuu') on the backend right?
PouchDB-Server has extracted the url routing logic it uses into another module, https://github.com/pouchdb/express-pouchdb, the README should give you an example of how to do that and you dont need the extra functionality provided by pouchdb-server

Resources