ENOENT ERROR using fs.unlink in a Express.js Simple APP? - javascript

js.And i'm creating a simple blog in express.js.
I use Typicode/lowdb as database , to create/update/delete, posts based on the id on a data.json file.And use the slug data in the json array to create/update/delete markdown posts with the Node.js File System API.On the delete side of the markdown posts i get an error that i don't understand.
{ [Error: ENOENT, unlink 'C:\Users\path\to\publicfolder\undefined.md']
errno: -4058,
code: 'ENOENT',
path: 'C:\\Users\\path\\to\\publicfolder\\undefined.md' }
I'm using fs.unlink like this to remove markdown posts:
var oldSlug = "public/"+req.params.slug+".md";
fs.unlink(oldSlug, function(err) {
if(err) {
console.log(err);
} else {
console.log("Deleted the old markdown file: " + oldSlug +"");
}
});
Here is some example of the code exposed by parts:
Example to create/update/delete Posts - Post.js
exports.index = function (req, res) {
res.render('post/index', { posts: db.list()});
};
exports.form = function (req, res) {
res.render('post/form');
};
exports.edit = function (req, res) {
var post = db.getById(req.params.id);
res.render('post/edit', {post: post})
}
exports.update = function (req, res) {
var slugTitle = slug(req.body.name).toLowerCase().split('.').join("");
var description = req.body.desc;
db.update({id: req.body.id, name: req.body.name, desc: req.body.desc,
slug: slugTitle});
//using this to rename and update markdown posts it work's
var oldPath = "public/"+req.body.slug+".md";
var newPath = "public/"+slugTitle+".md";
fs.unlink(oldPath, function(err) {
if(err) {
console.log(err);
} else {
console.log("Deleted the old markdown file : oldPath ");
}
});
fs.writeFile(newPath, description, function(err) {
if(err) {
console.log(err);
} else {
console.log("The post was updated as: newPath ");
}
});
res.redirect('/post');};
exports.remove = function (req, res) {
db.remove(req.params.id);
//using this to delete markdown posts i get the error
//changing req.params.slug to req.body.slug still gives the error
var oldSlug = "public/"+req.params.slug+".md";
fs.unlink(oldSlug, function(err) {
if(err) {
console.log(err);
} else {
console.log("Deleted the markdown file: " + oldSlug +"");
}
});
res.redirect('/post');};
Example on Server.js
app.get('/post', post.index);
app.get('/post/create', post.form);
app.post('/post/create', post.save);
app.get('/post/details/:id', post.details);
app.get('/post/edit/:id', post.edit);
app.post('/post/update', post.update);
app.get('/post/delete/:id', post.remove);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
Example of a index.jade
doctype
html
head
title
body
h1 Posts
ul
each item in posts
li Item #{item.name} - #{item.desc} - #{item.slug}
a(href='/post/details/#{item.id}') Details -
a(href='/post/edit/#{item.id}') Edit -
a(href='/post/delete/#{item.id}') Delete
div
p
a(href='post/create') Add new
The problem is on the exports.remove function in post.js file but why??I believe i'm identifying the markdown file to delete that corresponds to the Slug params from the document in the database or not? I Hope i'm making sense in the code.

The problem is that you are not passing the variable slug anywhere to your remove route. Since you are using GET it can't come from req.body, so you have to either pass it in the URL path or as query string.
Try changing these lines:
post.js
var oldSlug = "public/"+req.query.slug+".md";
index.jade
a(href='/post/delete/#{item.id}?slug=#{item.slug}') Delete

Related

How to send output image from node js child process to 'parent'?

I have a child process that is being called as follows:
server.js
app.get('/search', function (req, res) {
var cp = spawn('node', 'app.js');
cp.stdout.on('data', function(data) {
console.log('stdout: ' + data);
});
...
});
Currently app.js is utilizing chrome-headless' captureScreenshot function to generate a screenshot, which is then stored locally.
app.js:
const img = await Page.captureScreenshot({format: 'png', fromSurface: true});
fs.writeFile('./screenshot.png', img.data, 'base64', function (err) {
if (err) {
console.log(err);
}
});
It is not necessary to store the image locally, but rather upload it to a server. I am trying to find a way to get this functionality to work:
server.js V2
app.get('/search', function (req, res) {
var cp = spawn('node', 'app.js');
cp.stdout.on('data', function(data) {
upload_image(data);
});
...
});
app.js V2
const img = await Page.captureScreenshot({format: 'png', fromSurface: true});
//EXPOSE 'img' to parent via cp.stdout - How do I do this part?
});
You can send messages via fork()
server.js
const { fork } = require('child_process');
app.get('/search', function (req, res) {
const forked = fork('app.js');
forked.on('message', (data) => {
uploadImage(data.imageURL); // It will be send by parent.
}); ...
});
app.js
const img = await Page.captureScreenshot({format: 'png', fromSurface: true});
fs.writeFile('./screenshot.png', img.data, 'base64', function (err) {
if (err) {
console.log(err);
}
process.send({ imageURL: './screenshot.png' }); //You can send any data from here.
});
Here is the nice tutorial for you.
https://medium.freecodecamp.org/node-js-child-processes-everything-you-need-to-know-e69498fe970a
I hope it helped you.

How to get data in Angular 2 service with Mlab

import { Injectable } from '#angular/core';
#Injectable()
export class UserService {
constructor() {
console.log("Users service initialized");
}
getUsers(){
//Mlab URL
//Example: mongodb://user:password#ds129038.mlab.com:29038/database_name
}
}
Hi, i'm looking the way to get users in angular 2 service from a database in MLAB. How could I receive them and iterate results?
Regards,
In your app folder make a new folder and name it "server"
Inside "server" folder make two new folders and name the "models", and "routes"
In models folder create a javascript file and name it same as your collection name in mlab/mongodb. Example "datacollection1.js"
Inside datacollection1.js paste the following code:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const datacollection1Schema = new Schema({
varone: String,
vartwo: String,
varthree: String,
varfour: String
});
module.exports = mongoose.model('datacollection1', herodataSchema, 'datacollection1class');
Inside "routes" folder create a file and name it "api.js"
Paste the following code in api.js
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Datacollection1class = require('../models/datacollection1');
const db = "mongodb://:#ds155201.mlab.com:<12345>/";
mongoose.Promise = global.Promise;
mongoose.connect(db, function(err){
if(err) {
console.log("Error: " + err);
}
});
//Get all data
router.get('/datacollection1class', function(req, res) {
console.log("Get request for datacollection1class");
Datacollection1class.find({})
.exec(function(err, datacollection1class){
if(err) {
console.log("Error retrieving datacollection1class.");
} else {
res.json(datacollection1class);
}
})
});
//retrieve data by id
router.get('/datacollection1class/:id', function(req, res) {
console.log("Get request for sigle document");
Datacollection1class.findById(req.params.id)
.exec(function(err, datacollection1classsingle){
if(err) {
console.log("Error retrieving datacollection1classsingle.");
}
else
{
res.json(datacollection1classsingle);
}
})
});
//Add a single new documemt
router.post('/datacollection1classsingle', function(req, res){
console.log('Post a data set');
var newDatacollection1classsingle = new Datacollection1class();
newDatacollection1classsingle.varone = req.body.varone;
newDatacollection1classsingle.vartwo = req.body.vartwo;
newDatacollection1classsingle.varthree = req.body.varthree;
newDatacollection1classsingle.varfour = req.body.varfour;
newDatacollection1classsingle.save(function(err, insertedDatacollection1classsingle){
if (err) {
console.log('Error saving new hero data: '+err);
} else {
res.json(insertedDatacollection1classsingle);
}
});
});
//Update existing document
router.put('/hatacollection1class/:id', function(req, res) {
console.log('Update a video');
Datacollection1class.findByIdAndUpdate(req.params.id,
{
$set: {
varone: req.body.varone,
vartwo: req.body.vartwo,
varthree: req.body.varthree,
varfour: req.body.varfour
}
},
{
new:true
},
function(err, updatedDatacollection1classsingle) {
if(err){
res.send("Error updating Datacollection1class by id : "+err);
} else {
res.json(updatedDatacollection1classsingle);
}
});
});
// Delete a document
router.delete('/datacollection1class/:id', function(req, res) {
console.log('Deleting a datacollection1class');
Datacollection1class.findByIdAndRemove(req.params.id, function(err, deletedDatacollection1classsingle){
if (err) {
res.send("Error deleting Datacollection1class by id: "+err);
} else {
res.json(deletedDatacollection1classsingle);
}
});
});
Go to command prompt and using angular CLI create a class. Make sure Angular CLI is installed on your machine. Type in command prompt in your app folder
ng generate class datacollection1class
and hit enter. This will create a file named "datacollection1class.ts"
Inside datacollection1class.ts type the following code:
export class Datacollection1class {
_id: string;
varone: string;
vartwo: string;
varthree: string;
varfour: string;
}
You are all set. Now on your command prompt type:
ng build
Then on your command prompt type:
node server
Go to the browser and run "http://localhost:4200/api/datacollection1class" or if you have the id of the document, then "http://localhost:4200/api/datacollection1class/59305a02734d1d5068f2414e" or tey running it using postman
Feel free to ask questions. upvote if you liked the help.

TypeError: Cannot read property 'findAll' of undefined

I am developing a web app that uses angularjs, nodejs, and postgresql. I have two tables in my database, one for inventory and the other for client. I combined my index.js files, in my routes folder, in which both tables have a findAll function. When I put the two references for the tables in the index.js, only one works at a time. Here is the template that both tables use that includes findAll:
exports.getobjects = function(req, res) {
models.Object.findAll().then(function(objectss){
res.json(objects);
});
};
Has anyone done what I am trying to do?
UPDATE: Here is entire index.js file :
/*
* GET home page.
*/
var models = require("../models");
exports.index = function(req, res) {
res.render('index', {
title : 'title'
});
};
/* clients */
exports.getclients = function(req, res) {
models.Client.findAll().then(function(clients){
res.json(clients);
});
};
exports.saveclients = function(req, res) {
models.Client.create({
name: req.body.name,
ssn: req.body.ssn,
dln: req.body.dln,
dls: req.body.dls,
zip: req.body.zip,
email: req.body.email,
notes: req.body.notes,
}).then(function(clients){
res.json(clients.dataValues);
}).catch(function(error){
console.log("ops: " + error);
res.status(500).json({ error: 'error' });
});
};
/*inventory*/
exports.getunits = function(req, res) {
models.Unit.findAll().then(function(units){
res.json(units);
});
};
exports.saveunits = function(req, res) {
models.Unit.create({
name: req.body.text,
quant: reg.body.quant
}).then(function(units){
res.json(units.dataValues);
}).catch(function(error){
console.log("ops: " + error);
res.status(500).json({ error: 'error' });
});
};
You are doing your exports incorrectly. Here is an example of how to do it correctly.
Lets say I want to export 2 functions for a module this is a simple way to achieve it.
myModule.js
module.exports = {
awesomeMethod: function () {
},
coolMethod: function () {
}
}
Now to use it I would do the following
var myModule = require('./myModule');
myModule.awesomeMethod();
myModule.coolMethod();

How to delete document by _id using MongoDB and Jade (Express.js)?

I have successfully set up a database using mongodb, and I have managed to add new entries to my collection. However, when I use a similar method to delete, nothing happens.
Express.js code
router.post('/deleteproject', function(req, res) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/plugd';
MongoClient.connect(url, function(err, db) {
if (err) {
console.log("Unable to connect to server", err);
} else {
console.log('Connected to server');
var collection = db.collection('projects');
collection.remove(
{_id: new mongodb.ObjectID(req.body)}, function(err, result) {
if (err) {
console.log(err);
} else {
res.redirect("thelist");
}
db.close();
});
}
});
});
Jade code
h2.
ul
Projects
each project, i in projectlist
#project_list_item
a(href='#') #{project.owner} - #{project.project}
p #{project.ref1}
p #{project.ref2}
p #{project.ref3}
form#form_delete_project(name="deleteproject", method="post", action="/deleteproject")
input#input_name(type="hidden", placeholder="", name="_id", value="#{project._id}")
button#submit_project(type="submit") delete
I figured it out. Here is my fix for deleting data from a mongodb collection using a router in express.js.
Express.js
router.post('/deleteproject', function(req, res) {
var MongoClient = mongodb.MongoClient;
var ObjectId = require('mongodb').ObjectId;
var url = 'mongodb://localhost:27017/app';
MongoClient.connect(url, function(err, db) {
if (err){
console.log('Unable to connect to server', err);
} else {
console.log("Connection Established");
var collection = db.collection('projects');
collection.remove({_id: new ObjectId(req.body._id)}, function(err, result) {
if (err) {
console.log(err);
} else {
res.redirect("thelist");
}
db.close();
});
}
});
});
Jade code
extends layout
block content
h2.
Projects
ul
each project, i in projectlist
#project_list_item
a(href='#') #{project.owner} - #{project.project}
p #{project.ref1}
p #{project.ref2}
p #{project.ref3}
form#form_delete_project(name="deleteproject", method="post", action="/deleteproject")
input#input_name(type="hidden", placeholder="", name="_id", value="#{project._id}")
button#submit_project(type="submit") delete
The jade file is rendering to a page called 'thelist' that lists each item in the collection.
The form section handles the delete function for each item in the list.
This works for me as long as I keep Jade's indents happy :)
Try this and see if it works :
router.post('/deleteproject', function(req, res) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/plugd';
MongoClient.connect(url, function(err, db) {
if (err) {
console.log("Unable to connect to server", err);
} else {
console.log('Connected to server');
var collection = db.collection('projects');
collection.remove(
{_id: req.body}, function(err, result) {
if (err) {
console.log(err);
} else {
res.redirect("thelist");
}
db.close();
});
}
});
});
Since you're on MongoDB's Node.js Native Driver, you don't need to marshall _id inside ObjectId. You can directly specify the _id as string

Moved route from app.js to route.js and app no longer works

In my app.js file I had the code below and it worked as intended. I need to clean up my code, so I moved it to it's own route at routes/random and it no longer works because I get an error that states: "http://localhost:1337/random/1/1/testing 404 (Not Found)" and I am not sure why. My original code was in my app.js file when it was working was:
app.get('/random/:room/:userId/:message', function(req, res) {
fs.appendFile(room.number.toString(), req.params.message, function(err) {
if (err) {
console.log('error writing messages to file');
};
fs.readFile('./' + room.number, 'utf-8', function(err, data) {
if (err) {
if (err.fileNotFound) {
return this.sendErrorMessage('can\'t find the file, you linked it incorrectly');
}
console.log('error reading message file');
};
if (req.params.userId == 1) {
messages.user1.push(data);
} else {
messages.user2.push(data);
};
console.log(messages);
res.send(data);
fs.unlink(req.params.room, function(err) {
});
});
});
});
the new code includes the following for app.js
var express = require('express');
var app = express();
var fs = require('fs');
var random = require('./routes/random');
app.use('/random/', random);
app.use(express.static('public'));
app.use(express.static('public/js'));
app.use(express.static('public/images'));
and after I moved it, the route code is:
var express = require ('express');
var fs = require ('fs');
var random = express.Router();
random.get('/random/:room/:userId/:message', function(req, res) {
fs.appendFile(room.number.toString(), req.params.message, function(err) {
if (err) {
console.log('error writing messages to file');
};
fs.readFile('./' + room.number, 'utf-8', function(err, data) {
if (err) {
if (err.fileNotFound) {
return this.sendErrorMessage('can\'t find the file, you linked it incorrectly');
}
console.log('error reading message file');
};
if (req.params.userId == 1) {
messages.user1.push(data);
} else {
messages.user2.push(data);
};
console.log(messages);
res.send(data);
fs.unlink(req.params.room, function(err) {
});
});
});
});
module.exports = random;
Can anyone explain what I have done wrong that won't allow it to find the file?
In your code you are defining a route called random\random... in random.js, delete first random there, because middleware(app.use..) will direct all routes with /random to your router instance.
Your router is handling a url that starts with /random, and you attach this to your app under the path /random/. Remove one or the other (preferebly, the one inside the router).
I was able to fix it. Both comments above are correct, but it still was throwing errors due to my variables being undefined. I figured it out though so I am closing this question. Thank you both

Categories

Resources