Write EPIPE error when filling form using node-pdftk - pdftk

I am trying to fill a pdf form using nodejs.
Im trying to use node-pdftk package for the same.Did following steps:
Installed pdftk for windows
mapped the path to the environment variables PATH
installed node-pdf package
`const express = require('express')
const app = express()
const cors = require('cors')
const pdftk = require('node-pdftk');
const bodyParser = require('body-parser');
var multer = require('multer'); // v1.0.5
var upload = multer();
app.listen(8000, () => {
console.log('Server started!')
});
var pdfPath='OoPdfFormExample.pdf';
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));
var formdata = {
'Given Name': 'Swetha',
'Family Name': 'Gulapannavar'
}
app.post('/api/file', upload.array(), (req, res, next) => {
//var buffer=JSON.stringify(Buffer.from(req.body));
var buffer=Buffer.from(req.body)
pdftk
.input(pdfPath)
.fillForm(formdata)
.flatten()
.output()
.then(buffer => {
// Still returns a buffer
res.type('application/pdf'); // If you omit this line, file will
download
res.send(buf);
})
.catch(err => {
res.send(err.message)
// handle errors
});
});`
but i'm getting following error when i try to execute the same.
Write EPIPE error.

This could be caused by node-pdftk not being able to find the PDFtk binaries; your PATH variable may not be set correctly for the account running your web service. You can set the bin path directly inside of your application using node-pdftk's configure function, which is briefly described on the node-pdftk npm project page. If that doesn't work, try configuring the tempDir path.

Related

Minimal Sveltekit + pg integration fails with "status" error

I'm trying to get Postgres working with sveltekit and a very minimal example is giving me issues. This is probably a configuration thing but the error I'm getting back from sveltekit makes no sense to me.
I start by installing a new project:
npm create svelte#latest my-testapp
Then I install "pg" to get Postgres pooling:
npm i pg
Then I add a page under src/lib/db.js:
import { Client, Pool } from 'pg';
const pool = new Pool({
user: 'xxx',
host: 'xxx',
database: 'xxx',
password: 'xxx',
port: 5432,
})
export const connectToDB = async () => await pool.connect();
Finally I add src/hooks.server.js to give me access to the pool within routes:
import { connectToDB } from '$lib/db';
export const handle = async ({event, resolve}) => {
const dbconn = await connectToDB();
event.locals = { dbconn };
const response = await resolve(event);
dbconn.release();
}
The server fails to compile with a couple of these errors:
Cannot read properties of undefined (reading 'status')
TypeError: Cannot read properties of undefined (reading 'status')
at respond (file:///C:/Users/user/code/svelte/my-testapp/node_modules/#sveltejs/kit/src/runtime/server/index.js:314:16)
at async file:///C:/Users/user/code/svelte/my-testapp/node_modules/#sveltejs/kit/src/exports/vite/dev/index.js:406:22
Not sure where "status" is coming from, seems to be part of the initial scaffolding. Any help appreciated.
Also - if there is a more straightforward way to integrate pg with sveltekit then I'm happy to hear about it. Thanks
My bad - the hooks function wasn't returning the response.
Hooks.server.js should read:
import { connectToDB } from '$lib/db';
export const handle = async ({event, resolve}) => {
const dbconn = await connectToDB();
event.locals = { dbconn };
const response = await resolve(event);
dbconn.release();
return response
}

Parse Server - Image files' path returns localhost

I have deployed 2 Ubuntu servers on Azure. First, I have installed the Parse Server and the second, I installed MongoDB. (I have also put a ready db there from my previous server via mongorestore)
Everything works fine! Both Parse Server and MongoDB server. They also communicate well. The thing is, when I run my iOS app, it brings all data correctly, except images. I print the URL of an image and here's what it returned: http://localhost:1337/parse/files/filename.jpeg
If I replace localhost with my server's ip, the image is being fetched nicely!
Here's what I have on my index.js:
var express = require('express');
var ParseServer = require('parse-server').ParseServer;
var ParseDashboard = require('parse-dashboard');
var allowInsecureHTTP = true;
var path = require('path');
var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI;
if (!databaseUri) {
console.log('DATABASE_URI not specified, falling back to localhost.');
}
var api = new ParseServer({
databaseURI: databaseUri || 'mongodb://IP:27017/db',
cloud: './cloud/main.js',
appId: process.env.APP_ID || 'xxx',
masterKey: process.env.MASTER_KEY || 'xxx', //Add your master key here. Keep it secret!
fileKey: 'xxx',
serverURL: process.env.SERVER_URL || 'http://localhost:1337/parse', // Don't forget to change to https if needed
// Enable email verification
verifyUserEmails: false,
// The public URL of your app.
// This will appear in the link that is used to verify email addresses and reset passwords.
// Set the mount path as it is in serverURL
publicServerURL: 'http://localhost:1337/parse',
});
// Client-keys like the javascript key or the .NET key are not necessary with parse-server
// If you wish you require them, you can set them as options in the initialization above:
// javascriptKey, restAPIKey, dotNetKey, clientKey
var app = express();
// Serve static assets from the /public folder
app.use('/public', express.static(path.join(__dirname, '/public')));
// Serve the Parse API on the /parse URL prefix
var mountPath = process.env.PARSE_MOUNT || '/parse';
app.use(mountPath, api);
// Parse Server plays nicely with the rest of your web routes
app.get('/', function(req, res) {
res.status(200).send('Make sure to star the parse-server repo on GitHub!');
});
// There will be a test page available on the /test path of your server url
// Remove this before launching your app
app.get('/test', function(req, res) {
res.sendFile(path.join(__dirname, '/public/test.html'));
});
var port = process.env.PORT || 1337;
var httpServer = require('http').createServer(app);
httpServer.listen(port, function() {
console.log('parse-server-example running on port ' + port + '.');
});
// Set up parse dashboard
var config = {
"allowInsecureHTTP": true,
"apps": [
{
"serverURL": "http://localhost:1337/parse",
"appId": "xxx",
"masterKey": "xxx",
"appName": "name",
"production": true
}
],
"users": [
{
"user":"username",
"pass":"pass"
}
]
};
var dashboard = new ParseDashboard(config, config.allowInsecureHTTP);
var dashApp = express();
// make the Parse Dashboard available at /dashboard
dashApp.use('/dashboard', dashboard);
// Parse Server plays nicely with the rest of your web routes
dashApp.get('/', function(req, res) {
res.status(200).send('Parse Dashboard App');
});
var httpServerDash = require('http').createServer(dashApp);
httpServerDash.listen(4040, function() {
console.log('dashboard-server running on port 4040.');
});
One thing I noticed at Parse's documentation, is this: When using files on Parse, you will need to use the publicServerURL option in your Parse Server config. This is the URL that files will be accessed from, so it should be a URL that resolves to your Parse Server. Make sure to include your mount point in this URL.
The thing is that this documentation was written having in mind MongoDB, is on the same server with Parse, which in my case isn't.
Any ideas on what to do?
I had to replace the publicServerURL of parse server's config, from http://localhost:1337/parse to http://publicIP:1337/parse and everything worked out great!
If you want to work with files(images) download them, just use publicServerURL as mentioned #Sotiris Kaniras
I would add that the config.json is in ~/stack/parse/config.json. Also here is the difference between serverURL and publicServerURL
Difference between serverURL and publicServerURL on ParseServer
In my case, I needed to add publicServerURL parameter alongside with serverURL because it hasn't existed yet.
So both parameters(publicServerURL & serverURL) are complement, not mutually exclusive, use them both.

How to set options for json-server as a module?

Suppose we have the following command line to run a json-server (https://github.com/typicode/json-server):
json-server db.json --routes routes.json --port 8008 --delay 1000
If we were to run json-server as a module, how do we set these options? I can see the db.json defined and the port defined. But it is not clear how the rest of the options can be defined.
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middleWares = jsonServer.defaults();
server.use(middleWares);
router.render = (req, res) => {
console.log(req);
};
server.use(router);
server.listen(8008, () => {
console.log('JSON Server is running');
});
I found how to set the delay. This requires installing the connect-pause package, which is also used in the json-server code (https://www.npmjs.com/package/connect-pause):
npm install connect-pause
Then on the server.js file, I added the following a require('connect-pause') and used it in the json server app. Here is my code:
const fs = require('fs');
const pause = require('connect-pause');
const jsonServer = require('json-server');
const server = jsonServer.create();
const router = jsonServer.router('db.json');
const middlewares = jsonServer.defaults();
server.use(middlewares);
server.use(jsonServer.bodyParser);
//
// Define custom routes (routes.json)
//
var routes = JSON.parse(fs.readFileSync('routes.json'));
server.use(jsonServer.rewriter(routes));
...
server.use(pause(1000));
server.use(router);
server.listen(8008, () => {
console.log('JSON Server is running');
});
To set any other option varies wildly, but I mainly needed to know how to set the delay.

jupyter-js-services - how to save notebook

I'm trying to use jupyter as a backend for my system and now I play with examples from jupyter-js-api docs.
Using IKernel and INotebookSession I managed to execute simple code and get the response form kernel.
But I can's figure out how to extract the notebook itself. there's nothing like "saveNotebook()" in API. I try to execute session.renameNotebook(), it completes successfully, but no files appear in filesystem (tried different paths like "/tmp/trynote.ipynb" "trynote.ipnb" and so on...).
Here's the code, it is slightly edited example from http://jupyter.org/jupyter-js-services/ page
#!/usr/bin/env node
var jpt = require("jupyter-js-services");
var xr = require("xmlhttprequest");
var ws = require("ws");
global.XMLHttpRequest = xr.XMLHttpRequest;
global.WebSocket = ws;
// start a new session
var options = {
baseUrl: 'http://localhost:8889',
wsUrl: 'ws://localhost:8889',
kernelName: 'python',
notebookPath: 'trynote.ipynb'
};
jpt.startNewSession(options).then((session) => {
// execute and handle replies on the kernel
var future = session.kernel.execute({ code: 'print(5 * 5);' });
future.onDone = (msg) => {
console.log('Future is fulfilled: ');
console.log(msg);
};
future.onIOPub = (msg) => {
console.log("Message in IOPub: ");
console.log(msg);
};
// rename the notebook
session.renameNotebook('trynote2.ipynb').then(() => {
console.log('Notebook renamed to', session.notebookPath);
});
// register a callback for when the session dies
session.sessionDied.connect(() => {
console.log('session died');
});
// kill the session
session.shutdown().then(() => {
console.log('session closed');
});
});
Looking and ContentManager API it seems to work with already existing files, or creating new ones, but its unclear how is it bound to sessions.
More, even simplest try to use "newUntitled" function gives 404 response...
var contents = new jpt.ContentsManager('http://localhost:8889');
// create a new python file
contents.newUntitled("foo", { type: "file", ext: "py" }).then(
(model) => {
console.log(model.path);
}
);
I feel a bit disoriented with all this and would appreciate any explanations.
Thanks..

How to store binary data (PNG) in MongoDB via Mongoose?

I'm working on a site with a MEAN stack scaffolded from this yeoman.io generator: https://github.com/DaftMonk/generator-angular-fullstack, and I'm trying to upload some image files to MongoDB in binary form. Here is my git repo for the project:
https://github.com/peter-atlanta/personal-site
I've followed #aheckmann's GIST to a tee: https://gist.github.com/aheckmann/2408370,
But I keep getting errors about how my files can't be found, i.e.
Error: ENOENT, no such file or directory '../../client/assets/images/github.png'
at Error (native)
at Object.fs.openSync (fs.js:500:18)
at Object.fs.readFileSync (fs.js:352:15)
at Immediate.<anonymous> (/Users/peterward/petergrayward/blog/server/config/imageToMongo.js:43:21)
at Immediate._onImmediate (/Users/peterward/petergrayward/blog/node_modules/mongoose/node_modules/mquery/lib/utils.js:137:16)
at processImmediate [as _immediateCallback] (timers.js:358:17)
Clearly, though, the png in question is located in that directory, and I've even tried moving the directory server-side to no avail.
Why can't a file/directory entry-point be found?
When it comes to storing small files in MongoDb, many answers which rely on Mongoose will also depend on using GridFS. If you are okay with simply storing files in MongoDB without relying on GridFS and Mongoose then try the following. (This answer is in TypeScript which I think is easier to read, but I can post the transpiled JavaScript if need be.)
import mongodb = require("mongodb");
const URI = 'mongodb://...';
var dbPromise = new Promise<mongodb.Db>(function (resolve, reject) {
mongodb.MongoClient.connect(URI, function (err, db) {
resolve(db);
});
});
import express = require("express");
var app = express();
import path = require("path");
import multer = require("multer");
var upload = multer({ dest: 'uploads/' });//saving files on filesystem seems to be a requirement
import fs = require("fs");
interface IFile {
name : string;
binary : mongodb.Binary;
}
//<input type="file" type="file" id="png1" name="png1" />
app.post("/file-upload", upload.single("png1"), function (req, res) {
let f = req.file;
fs.readFile(f.path, function (err, buffer) {
dbPromise.then(db => {
let file : IFile = {
name: f.originalname,
binary: new mongodb.Binary(buffer)
};
db.collection('files').insertOne(file, function(err, result) {
if (err) {
res.json(500, err);
}
console.log(`${result.insertedId} ${result.insertedCount}`);
});
});
})
});