I am trying to use the html-pdf node module to generate pdfs from html. I am currently running this using the cloud9 IDE.
My code is:
var fs = require("fs");
var pdf = require('html-pdf');
var html = fs.readFileSync('./test.html', {encoding: 'utf8'});
var options = { format: 'Letter' };
app.post('/pdf',function(req, res) {
pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
if (err) return console.log(err);
console.log(res); // { filename: '/app/businesscard.pdf' }
});
});
I get the following Error:
[Error: Fontconfig warning: ignoring C.UTF-8: not a valid language tag]
Does anyone know how i can resolve this issue?
This is due to a bug in fontconfig. You can see here
Open your terminal and execute locale -a you will see list of fonts. Then select it like LC_ALL=C
may it can help
Related
I'm new to Next.js, and I'm trying to use wkhtmltoimage but I can't seem to send the generated image stream as a response in my Next.js API.
const fs = require('fs')
const wkhtmltoimage = require('wkhtmltoimage').setCommand(__dirname + '/bin/wkhtmltoimage');
export default async function handler(req, res) {
try {
await wkhtmltoimage.generate('<h1>Hello world</h1>').pipe(res);
res.status(200).send(res)
} catch (err) {
res.status(500).send({ error: 'failed to fetch data' })
}
}
I know I'm doing plenty of stuff wrong here, can anyone point me to the right direction?
Since you're concatenating __dirname and /bin/wkhtmltoimage together, that would mean you've installed the wkhtmltoimage executable to ./pages/api/bin which is probably not a good idea since the pages directory is special to Next.js.
We'll assume you've installed the executable in a different location on your filesystem/server instead (e.g., your home directory). It looks like the pipe function already sends the response, so the res.status(200).send(res) line will cause problems and can be removed. So the following should work:
// ./pages/api/hello.js
const homedir = require("os").homedir();
// Assumes the following installation path:
// - *nix: $HOME/bin/wkhtmltoimage
// - Windows: $env:USERPROFILE\bin\wkhtmltoimage.exe
const wkhtmltoimage = require("wkhtmltoimage").setCommand(
homedir + "/bin/wkhtmltoimage"
);
export default async function handler(req, res) {
try {
res.status(200);
await wkhtmltoimage.generate("<h1>Hello world</h1>").pipe(res);
} catch (err) {
res.status(500).send({ error: "failed to fetch data" });
}
}
In a Node project, I want to show the contents of a Winston log file in a React interface. Reading the file:
let content;
fs.readFile("path", "utf-8", function read(err, data) {
if (err)
throw err;
content = data;
});
I send them to the interface:
router.get("/", function (req, res) {
res.status(200).send(JSON.stringify(content));
});
And i get the content in a .jsx file:
getLogs().then(res => {
let datafromfile = JSON.parse(res);
// Use the data
return;
}).catch(err => {
return err.response;
});
The issue i am having is that fs converts all the data into a string (since i am putting the utf-8 encoding and do not want to be returned a buffer) and therefore i cannot manipulate the objects in the log file to show them structurally in the interface. Can anyone guide how to approach this problem?
I have not debugged this, but a lot of this depends on whether or not the the Winston file your loading actually has JSON in it.
If it does then JSONStream is your friend and leaning through or through2 is helpful you in node (streams).
following, code/pseudo
router.get("/", function (req, res) {
const logPath = ‘somePath’; // maybe it comes from the req.query.path
const parsePath = null; // or the token of where you want to attemp to start parsing
fs.createReadStream(logPath)
.pipe(JSONStream.parse(parsePath))
.pipe(res);
});
JSONStream
fs.createReadStream and node docs
through2
I am currently using the python-shell module in a Node based web interface. The issue I am having is mostly syntactical. The code below shows the generation of a python script.
var PythonShell = require('python-shell');
PythonShell.run('my_script.py' function (err) {
if (err) throw err;
console.log('finished');
}):
This is just an example script from here. How do I relate this to node's
var procc = require('child_process'.spawn('mongod');
procc.kill('SIGINT');
The documentation states that PythonShell instances have the following properties:
childProcess: the process instance created via child_process.spawn
But how do I acutally use this? There seems to be a lack of examples when it comes to this specific module
For example -
var python_process;
router.get('/start_python', function(req, res) {
const {PythonShell} = require("python-shell");
var options = {
pythonPath:'local python path'
}
var pyshell = new PythonShell('general.py');
pyshell.end(function (err) {
if (err) {
console.log(err);
}
});
python_process = pyshell.childProcess;
res.send('Started.');
});
router.get('/stop_python', function(req, res) {
python_process.kill('SIGINT');
res.send('Stopped');
});
I'm trying to copy an image from a folder to another using fs-extra module .
var fse = require('fs-extra');
function copyimage() {
fse.copy('mainisp.jpg', './test', function (err) {
if (err)
return console.error(err)
});
}
This is my directory
and this is the error I get all the time:
Error {errno: -4058, code: "ENOENT", syscall: "lstat", path:
"E:\mainisp.jpg", message: "ENOENT: no such file or directory, lstat
'E:\mainisp.jpg'"}
and by changing destination to ./test/ I get this error
Error {errno: -4058, code: "ENOENT", syscall: "lstat", path:
"E:\Development\Node apps\Node softwares\Digital_library\mainisp.jpg",
message: "ENOENT: no such file or directory, lstat 'E:\Devel…
apps\Node softwares\Digital_library\mainisp.jpg'"}
Note: I'm not testing this in browser. It's an Nwjs app and the pics of error attached are from Nwjs console.
You can do this using the native fs module easily using streams.
const fs = require('fs');
const path = require('path');
let filename = 'mainisp.jpg';
let src = path.join(__dirname, filename);
let destDir = path.join(__dirname, 'test');
fs.access(destDir, (err) => {
if(err)
fs.mkdirSync(destDir);
copyFile(src, path.join(destDir, filename));
});
function copyFile(src, dest) {
let readStream = fs.createReadStream(src);
readStream.once('error', (err) => {
console.log(err);
});
readStream.once('end', () => {
console.log('done copying');
});
readStream.pipe(fs.createWriteStream(dest));
}
Try:
var fs = require('fs-extra');
fs.copySync(path.resolve(__dirname,'./mainisp.jpg'), './test/mainisp.jpg');
As you can see in the error message, you're trying to read the file from E:\mainisp.jpg instead of the current directory.
You also need to specify the target path with the file, not only the destination folder.
Try:
const fs = require('fs');
fs.copyFileSync(src, dest);
I'm making a node/express app and am querying a test json file using npm request-promise. Node is spitting out the following error in my <title> tags:
Error: <title>Invalid URI "../testJSON/user.json"</title>
I believe my pathing is correct, so am unsure why it's an invalid URI.
I've also provided the entire project path URI with the same issue:
return rp('http://localhost:3000/app/testJSON/user.json');
User Service:
module.exports = {
getUserData: function(){
var options = {
uri : '../testJSON/user.json',
method : 'GET'
}
return rp(options);
}
}
User Controller:
var User = require('../services/User.service');
User.getUserData()
.then(function(data){
res.render('pages/userdata', {
title: 'User Data',
content: JSON.parse(data)
});
})
.catch(function(err){
console.log(err);
});
Pathing:
User Service: projectroot/app/services/userService.js
User json file: projectroot/app/testJSON/user.json
Update: trying with node fs to fetch local file
fs = require('fs');
module.exports.index = function (req, res) {
fs.readFile('../testJSON/user.json', 'utf8', function (err,data) {
if (err) {
return console.log(err);
}
res.render('pages/user', {
title: 'User',
content: JSON.parse(data)
});
});
...
Node error:
{ [Error: ENOENT, open '../testJSON/user.json'] errno: -2, code:
'ENOENT', path: '../testJSON/user.json' }
Relative paths (starting with ../ or ./) are relative to the current working directory. If you want to read a file relative to the current JS source file, you need to prefix the path with __dirname, which is the directory where the current JS source file resides:
fs.readFile(__dirname + '/../testJSON/user.json', ...);
Or the more elaborate (but probably more correct) way:
var path = require('path);
...
fs.readFile(path.join(__dirname, '../testJSON/user.json'), ...);