Below is my app.js file. When I run the following code it shows "swarm listening on" and "file-path" and then nothing happens.
I am also running daemon on another command prompt listening api on 5001.
I think node is not getting initiated thats why it never becomes ready.
var express = require('express');
var app = express();
var ipfsAPI = require('ipfs-api')
var ipfs = ipfsAPI('localhost', '5001', {protocol: 'http'})
const IPFS = require('ipfs');
// Spawn your IPFS node \o/
const node = new IPFS();
var multer = require('multer');
var upload = multer({ dest: './z000000000'});
var fs = require('fs');
/** Permissible loading a single file,
the value of the attribute "name" in the form of "recfile". **/
var type = upload.single('filer');
app.post('/upload', type, function (req,res) {
/** When using the "single"
data come in "req.file" regardless of the attribute "name". **/
var tmp_path = req.file.path;
console.log(tmp_path);
//
node.on('ready', () => {
node.id((err, id) => {
if (err) {
return console.log(err)
}
console.log(id)
})
var data = fs.readFileSync('./'+tmp_path);
console.log("Synchronous read: " + data.toString());
let files = [
{
path: './'+tmp_path,
content: data
}
]
node.files.add(files, function (err, files) {
if (err) {
console.log(err);
} else {
console.log(files)
}
})
})
//
res.end();
});
var server = app.listen(8081, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
Use ipfsAPI:
var ipfs = ipfsAPI('localhost', '5001', {protocol: 'http'}
To get the ID of node:
ipfs.id()
.then(res => {
showStatus(`daemon active\nid: ${res.ID}`, COLORS.success)
doYourWork()
})
.catch(err => {
showStatus('daemon inactive', COLORS.error)
console.error(err)
})
Find Documentation here: https://github.com/ipfs/js-ipfs-api
Related
In my express app, generated with express-generator, I want to use the io of socket.io in some other controller files to emit data to client sockets. My approach is below, but I get the following error with that. It would be a great favor if someone can help me in this case.
(node:11376) UnhandledPromiseRejectionWarning: TypeError: io.emit is not a function
at F:\backend\controllers\LessonController.js:169:9
In the express apps, generated by express-generator, the process of creating the server happens in the /bin/www.js. I tried importing the io instance from there and use it in some other file, but it didn't work.
bin/www.js
#!/usr/bin/env node
var app = require('../app');
var debug = require('debug')('backend:server');
var http = require('http');
var port = normalizePort(process.env.PORT || '8080');
app.set('port', port);
var server = http.createServer(app);
const io = require('socket.io')(server);
server.listen(port);
server.on('error', onError);
server.on('listening', onListening);
// several other functions are omitted for brevity
module.exports = io;
LessonController.js
const Lesson = require('../models/Lesson');
const Course = require('../models/Course');
const User = require('../models/User');
const io = require('../bin/www')
var _ = require('lodash');
module.exports = {
addComment: async (lessonId, userId, content, callback) => {
const newData = {
comments: {
user: userId,
content: content,
},
};
Lesson.findOneAndUpdate({ _id: lessonId }, { $push: newData }, {new: true})
.exec()
.then(
function (data) {
if (data) {
io.emit("comment_"+lessonId,data)
callback(null, data);
} else if (err) {
callback(err, null);
}
}
)
}
};
You can try to export the socket.io instance to the global level and access that as needed.
My project was also created with express-generator, therefore, follows the same template.
In my project, I would like to count the current number of active users in home page.
Here is an example:
bin/www
#!/usr/bin/env node
const app = require('../app');
const http = require('http').Server(app);
const io = require('socket.io')(http)
http.listen(process.env.PORT);
io.on('connection', (socket) => {
const qtd = socket.client.conn.server.clientsCount;
io.emit('novaconexao', qtd);
socket.on('disconnect', () => {
io.emit('disconnecteduser', qtd - 1);
});
});
app.set('socketio', io);//here you export my socket.io to a global
console.log('Microsservice login listening at http://localhost:%s', process.env.PORT);
server/index.js
const router = require('express').Router();
router.get('/', (req, res) => {
const io = req.app.get('socketio'); //Here you use the exported socketio module
console.log(io.client.conn.server.clientsCount)
io.emit('new-user', {qtd: io.client.conn.server.clientsCount})
res.status(200).json({ msg: 'server up and running' });
})
module.exports = router;
Following this strategy, you can use socketio in any route in your application.
Here is a solution
Create a module io.js
const sio = require('socket.io');
let io = null;
module.exports = {
//Initialize the socket server
initialize: function(httpServer) {
io = sio(httpServer);
io.on('connection', function(socket) {
console.log('New client connected with id = ', socket.id);
socket.on('disconnect', function(reason) {
console.log('A client disconnected with id = ', socket.id, " reason ==> ", reason);
});
});
},
//return the io instance
getInstance: function() {
return io;
}
}
In bin/www.js
var server = http.createServer(app);
require('path_to_io_js/io').initialize(server);
In your controllers / LessonController.js
//require the io module
const socket = require('path_to_io_js/io');
module.exports = {
addComment: async (lessonId, userId, content, callback) => {
const newData = { comments: { user: userId, content: content, }, };
Lesson.findOneAndUpdate({ _id: lessonId }, { $push: newData }, { new: true })
.exec().then(function (data) {
if (data) {
//get the io instance
const io = socket.getInstance();
io.emit("comment_" + lessonId, data)
}
callback(null, data);
}).catch(err => {
callback(err);
})
}
};
Create socketInstance.js
let io = null;
// set this when you initialize the io
const setSocketInstance = (ioInstance) => {
io = ioInstance;
};
// you can call this anywhere
const getSocketInstance = () => {
return io;
};
inside socket.js where you initialize io
const setSocketInstance = require("./socketInstance");
const initializeIO = (server) => {
const io = require("socket.io")(server, {
cors: {
origin: "*",
methods: ["GET", "POST"],
},
});
// as soon as we initialize the io, we set the instance
setSocketInstance(io);
// ....
};
Now you can call getSocketInstance anywhere in your app.
So I have this main server file index.js:
const express = require('express')
const app = express()
const route = require('./route')
app.use('/main', route)
app.listen(3000)
and then I have the route.js file:
const express = require('express')
const router = express.Router()
router.get('/', (req, res) => {
res.send('Hello from main')
})
module.exports = router
As the title implies, how could I make a global mongodb connection so that I don't have to make a new connection to the database on every route?
Thanks!
I'm surprised there is no answer on SO to this. The most common pattern is to initialize your database connection in a separate module and to import it in any file that needs it.
The below was taken from this longer article https://itnext.io/how-to-share-a-single-database-connection-in-a-node-js-express-js-app-fcad4cbcb1e and was written in callback style. I've updated it a little to be promise based below:
/* Callback Style */
const assert = require("assert");
const client = require("mongodb").MongoClient;
const config = require("../config");
let _db;
module.exports = {
getDb,
initDb
};
function initDb(callback) {
if (_db) {
console.warn("Trying to init DB again!");
return callback(null, _db);
}
client.connect(config.db.connectionString,
config.db.connectionOptions, connected);
function connected(err, db) {
if (err) {
return callback(err);
}
console.log("DB initialized - connected to: " +
config.db.connectionString.split("#")[1]);
_db = db;
return callback(null, _db);
}
}
function getDb() {
assert.ok(_db, "Db has not been initialized. Please called init first.");
return _db;
}
/******************************************************************/
//The client
const initDb = require("./db").initDb;
const getDb = require("./db").getDb;
const app = require("express")();
const port = 3001;
app.use("/", exampleRoute);
initDb(function (err) {
app.listen(port, function (err) {
if (err) {
throw err; //
}
console.log("API Up and running on port " + port);
});
);
function exampleRoute(req, res){
const db = getDb();
//Do things with your database connection
res.json(results);
}
Here's a promise based version without semi-colons which is how I might do it for itself. These functions would all become candidates for reuse between projects.
const assert = require("assert")
const client = require("mongodb").MongoClient
const config = require("../config")
let _db
module.exports = {
getDb,
initDb
}
function initDb() {
if (_db) {
console.warn("Trying to init DB again!");
return Promise.resolve(true)
}
return client.connect(config.db.connectionString,
config.db.connectionOptions)
}
function getDb() {
assert.ok(_db, "Db has not been initialized. Please called init first.")
return _db
}
//////////////////////
const {initDb, getDb} = require("./db")
const app = require("express")()
const port = 3001
app.use("/", exampleRoute)
initDb().
then(_ =>bootServer(port))
.catch(console.log)
function bootServer(port) {
app.listen(port, function (err) {
if (err) {
Promise.reject(err)
}
console.log("API Up and running on port " + port)
Promise.resolve()
})
}
function exampleRoute(req, res){
const db = getDb();
//Do things with your database connection
res.json(results);
}
This below code gives output for GET user list but i want
it also to delete and post some element in test.json file memory :
delete data using name i.e localhost:8080/alpha
and when we add user using post in api client it should save in test.json as new element with existing element
So can anyone edit the following code for me :)
test.json
[
{
"name":"alpha",
"password": "123"
},
{
"name":"beta",
"password": "321"
}
]
//main.js
var express = require('express');
var app = express();
var fs = require("fs");
app.get('/listUsers', function (req, res) {
fs.readFile(__dirname + "/" + "test.json", 'utf8', function (err, data) {
if (err) { return console.log(err); }
console.log("All users :" + data);
res.end(data);
});
});
app.delete('/:name', function (req, res) {
});
app.post('/postUser', function (req, res) {
});
var server = app.listen(3000, function () {
var host = server.address().address
var port = server.address().port
console.log("Example app listening at http://%s:%s", host, port)
})
I have a simple node app that parses a csv file into a string. In my server file, I call a module that runs makes a stream and pipes it into my parser.
The problem is that is code works perfectly the first time it is run, but fails after that. I've gotten a "Write after End" error so I believe there is something wrong with the stream or parser variable not being reset properly after each use. Thanks for any help!
const express = require('express');
const app = express();
const path = require('path');
const port = process.env.PORT || 3000;
const formidable = require('formidable');
const parser = require('./csvparse.js');
const fs = require('fs');
//send the index page on a get request
app.listen(port, () => console.log('Example app listening on port: ' + port));
app.get('*', (req, res) => res.sendFile(path.join(__dirname + "/index.html")));
app.post('/upload', function(req, res) {
//upload the file from the html form
var form = new formidable.IncomingForm();
form.parse(req,function(err, fields, files) {
if (err) throw err;
//get the path to the uploaded file for the parser to use
var filePath = files.spinFile.path;
parser(filePath, function(data) {
if (data == null) {
res.sendFile(path.join(__dirname + "/index.html"));
}
res.send("<code>" + data + "</code>");
});
});
});
The module export function looks like this:
module.exports = function(filePath, cb) {
var stream = fs.createReadStream(filePath);
stream.pipe(parser);
//when the stream is done, songsLog is complete and ready to be returned
stream.on('close', function() {
cb(songsLog);
});
};
Try wrapping the contents of your module.exports in another function.
module.exports = function(filepath, cb) {
function parse(filepath) {
const stream = fs.createReadStream(filepath)
etc...
}
return {
parse
}
}
then from your route, call parser.parse('file.txt') and you should have a new read stream.
I have nodejs project running on centos 7.
I'm trying to run my nodejs project with the command node start.js aswell tried sudo node start.js but tends to be hanging up, i included a screenshot too, which you can find there: http://prntscr.com/g4ogcf
Can anybody help me with this? I'm quite clueless about that because it doesn't return any errors aswell.
My start.js application code:
const app = require('express')();
const fs = require('fs');
const server = require('http').Server(app);
const cors = require('cors');
const express = require('express');
const Database = require('./Database.js');
const db = new Database();
const cfg = require('./config/config.json');
const io = require('socket.io')(cfg.client.socket_port);
const Router = require('./Router')(db, io);
app.listen(cfg.client.server_port);
app.use(cors());
app.get('/', (req, res) => {
fs.readFile(`${__dirname}/../public/client/app/index.html`, (err, data) => {
if (err)
throw err;
res.send(data.toString())
});
});
app.get('/media', (req, res) => {
if (req.query.cfg) {
res.set('Content-Type', 'application/javascript');
fs.readFile(`${__dirname}/config/config.json`, (err, data) => {
if (err)
throw err;
res.send(`export default ${JSON.stringify(JSON.parse(data).client)}`);
});
}
res.set('Content-Type', 'image/jpeg');
if (req.query.avatar) {
db.getAvatarImg(req.query.avatar).then(x => {
var img = x[0] ? x[0].img : '';
const data = img.replace(/^data:image\/\w+;base64,/, "");
const buf = new Buffer(data, 'base64');
res.send(buf);
});
}
if (req.query.background) {
db.getBackgroundImg(req.query.background).then(x => {
var img = x[0] ? x[0].img : '';
const data = img.replace(/^data:image\/\w+;base64,/, "");
const buf = new Buffer(data, 'base64');
res.send(buf);
});
}
if (req.query.post) {
db.getPostImg(req.query.post).then(x => {
var img = x[0] ? x[0].img : '';
const data = img.replace(/^data:image\/\w+;base64,/, "");
const buf = new Buffer(data, 'base64');
res.send(buf);
});
}
});
app.use(express.static(`${__dirname}/../public/`));
Put
console.time('app started');
before all of the require statements and
console.timeEnd('app started');
at the end of the start.js code. With the help of this, you can check whether your application hanged or initialized successfully.
Nothing is wrong with the program.
Just update app.listen(cfg.client.server_port); to
app.listen(cfg.client.server_port, ()=>{
console.log("server started at port "+cfg.client.server_port);
});
This will log on the console a text telling you that the server has started.