Node JS : invalid data error using execFileSync - node.js

I am stuck on a NodeJS error while trying to execute a script and get the output of it.
I get the following error :
TypeError: invalid data
at WriteStream.Socket.write (net.js:623:11)
at Object.execFileSync (child_process.js:482:20)
at doRender (/test/apps/application/routes/TEST.js:1786:26)
I guess it comes from a misuse of the NodeJS native execFileSync function, but I've tried a lot of things to match the documentation without any success so far.
Here is my code :
router.get("/stat", authReader, function (req, res) {
//Current file is in application/routes
var doRender = function (req, res) {
var output;
//I want to execute application/scripts/test.bash
output= child_process.execFileSync("test.bash",[], {
cwd: "../scripts"
});
result= processDataFromCSV(output);
//processing data in response
res.render(acronym + "_test", {
title: "CSV output",
result: result,
});
}
doRender(req, res);
}
Could you please help me to understand what I am doing wrong ? Any help is greatly appreciated.

Verify that your test.bash is executable, or run it like /bin/bash test.bash using child_process.execSync(). For more information look at this answer by Sravan here;

Related

How to update postgres jsonb with dynamic variables in nodejs? [duplicate]

I have following setup for my project, using the pg node-postgres package:
The simple table 'tmp' looks like this:
According to jsonORG and the postgres docs the object:
{"foo" : true}
is syntactically valid JSON, and when using the pgAdmin Query-tool with:
UPDATE tmp SET data = '{"foo": false}' WHERE id = '1'
works fine, but when i try updating my table through my express route using pg:
router.put('/updateTMP', (req, res) => {
// I use dummies in this case instead of req.body.someKey for testing purposes
let dummyJSON = {"foo":true};
let dummyID = 1;
pg.query(`UPDATE tmp SET data = '${dummyJSON}' WHERE id = '${dummyID}'`, (errUpdate, responseUpdate) => {
if (!errUpdate) { // NO ERROR
res.json({success: true, message: responseUpdate});
}
else { // ERROR
console.log(dummyJSON);
console.log(errUpdate);
res.json({success: false, message: errUpdate});
}
})
})
I get the following error from the database:
error: invalid input syntax for type json
I've tried the to_json function from postgresql and the to-json package from npm in the express route - all with the same negative result.
Am i missing some fundamental understanding or is it some formating/quoting-issue?
Thanks in advance for your ideas! ;)
ps: And yes - I've read through this, and that article..
I had the same problem. Try converting your JS object to string using JSON.stringify() before passing it into the query as pg won't always do that for you automatically.
See this issue on GitHub for more info.

DiscordJS + NodeJS: SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>)

Having an issue where I will randomly get this error after about an hour of my code running.
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
Here is my code:
function matchMaking() {
setInterval(function() {
fs.readFile('./rankedQueue.json', 'utf8', function(err, data) {
const file = JSON.parse(data); //The line the error occurs
if (err) {
console.log(err)
} else {
//lots of code here
}
})
}, 10 * 1000)
}
edit: This is the content of the JSON file.
{
"queue": [],
"waiting": [],
"lowLevel": [],
"placeHolder": [
{
"test": "test"
}
]
}
The arrays are being pushed to, and then spliced a couple times a minute.
After searching here and some forums, I've tried using fs.readFileSync, which makes the code not run at all. And now I'm finding some specific examples of this error that I can't quite seem to make the solutions apply to me. If anyone has any idea of what I should be changing, It would be appreciated.
Thanks in advance.
As the errors said data is not in json type
Can you make sure the file is valid and it's is what JSON.parse() can parse
How to use fs.readFileSync
Using fs.readFileSync returns a buffer. You can easily convert the buffer into something readable. You use buffer.toString('ascii'). Also, fs.readFile has a callback argument while readFileSync DOESN'T. What I think you were doing about readFileSync was:
fs.readFileSync('./rankedQueue.json', 'utf8', function(err, data) {
const file = JSON.parse(data); //The line the error occurs
if (err) {
console.log(err)
} else {
//lots of code here
}
})
But you should actually be doing this:
var data = fs.readFileSync('./rankedQueue.json');
var JSON = JSON.parse(data.toString('ascii'));
You could drop the 'ascii'.
Incorrect / Hacky Answer
Use require instead. Node.JS has it so it can parse a JSON file for you. Keep in mind that the way you require a file compared to fs is different.
If your code is located at /project/foobar/code.js
JSON is at /project/rankedQueue.json
fs automatically goes to the top of where your project folder is, e.g. /project & So ./rankedQueue.json
require does not do this, and stays in the folder where the file is. You have to add ../ for every folder you want to go above. So: ./../rankedQueue.json.
I'd suggest also running your JSON through a validator as well so it can tell you whats wrong.

Node Js API : where the undefined comes from?

I write this code to get the array from url. this is the url : http://localhost:3000/main?a=aaa.jpg&a=bbb.jpg
And here is the code :
//Define module
var express = require('express');
var app = express();
const { exec } = require('child_process');
//extract function
function extract (req,res,next){
res.write(`filename : ${req.query.a}`); //kt page
console.log(req.query.a);//kt terminal
next();
};
//main function
function main (req,res,next){
res.write('\nkuor dok \n');
res.end();
};
app.use(extract);
app.get('/main',main);
app.listen(3000);
This is the output in terminal.
Array(2) ["aaa.jpg", "bbb.jpg"]
undefined
The question is where the undefined comes from? It affected everything i need to do. The array is perfectly fine. But suddenly undefined comes out. Can anyone help me. Thank you in advance.
I tried the code you provided above and i got only the array in the terminal
[ 'aaa.jpg', 'bbb.jpg' ]
When i tried the url in the browser i got
filename : aaa.jpg,bbb.jpg
kuor dok
as the output. i didn't get any undefined
I see that you are trying to define extract function as a middleware. It will be executed for every request
try to comment app.get:
app.use(extract);
//app.get('/main', main);
app.listen(3000);
Then try to make the request
GET: http://localhost:3000/main?a=aaa.jpg&a=bbb.jpg
you will get
[ 'aaa.jpg', 'bbb.jpg' ]
You are handling the request twice. First by the global middleware, the second time by app.get() that calls also the middleware extract before main
As I see app.get don't handle your query params and you got undefined due to an empty object try to log: req.query intead of req.query.q
function extract(req, res, next) {
res.write(`filename : ${req.query.a}`); //kt page
console.log(req.query); //kt terminal
next();
};

TypeError: invNum.next is not a function

I have tried this code :
const invNum = require('invoice-number');
router.post('/checkout', async (req, res, next) => {
if (!req.session.cart) {
return res.redirect('/pos/');
}
var saleList = Sale.find().sort({ _id: -1 }).limit(1); // removed (err, data)=>{} to simply view it is working tested already
var settings = await Setting.find({}); // removed try and catch to simply view it is working tested already
var ticketNumber;
ticketNumber = !saleList ? invNum.next('0000000') : invNum.next(saleList.ticket_number);
var sale = new Sale({
ticket_number:ticketNumber,
cart: req.session.cart,
created_at: new Date()
});
sale.save((err, product) => {
createReceipt(settings, req.session.cart, "receipts/"+ticketNumber+".pdf");
req.session.cart = null;
res.redirect('/pos/');
});
});
I got this error:
TypeError: invNum.next is not a function
The problem is with invNum.next().
invNum.next() is a Node.js module to generate invoice number sequentially installed from npm.
Example:
invNum.next('2017/08/ABC001')
// => 2017/08/ABC002
I have tried already suggestions from previous stackoverflow posts by trying Promises or await async function in order to get this code to work. Hopefully, you can help or suggest something. Thank you.
There is a problem in version of invoice-number module. In the npm it is showing as 1.0.6 but in the GitHub repository it has 1.0.5 in the package.json file.
https://github.com/amindia/invoice-number.
I have tested this module by taking from Github repository and it's working fine.
Please take the source of this module from the given link it will works fine.
Seems to be some error in the module. I tried the below code snippet on RunKit
https://runkit.com/embed/ws2lv1y38mt4
var invNum = require('invoice-number')
try{
invNum.next('sdfsd1')
} catch(e){
console.log(e)
}
Getting the same error
I got this error:
TypeError: invNum.next is not a function UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()
What is the output when you use the console.log on invNum?
Also use try catch and inside call invNum.next with await. Maybe something inside this function is throwing an error.
Edit: as jfriend00 says, if an plain text (like your "0000...") is working, probably the saleList is returning some error and you are not catching or treating the error.
Edit2: The last update on this NPM code is from 1 year ago and fewer people used this lib, probably is broken.
There is some part of the code from the index.js of the lib:
function _next (invoiceNumber) {
if (!invoiceNumber)
throw new Error('invoiceNumber cannot be empty')
var array = invoiceNumber.split(/[_/:\-;\\]+/)
var lastSegment = array.pop()
var priorSegment = invoiceNumber.substr(0, invoiceNumber.indexOf(lastSegment))
var nextNumber = alphaNumericIncrementer(lastSegment)
return priorSegment + nextNumber}
var api = { next: _next}
module.exports = api

Unable to use getElementsByTagName("body")

Here's the code that results in an error each time I run it. My goal is to scrap the content from the URL, remove all HTML, and return it:
console.log("Fetching: " + inputData.tweeturl);
fetch(inputData.tweeturl)
.then(function(res) {
return res.text();
}).then(function(body) {
var rawText = body.getElementsByTagName("body")[0].innerHTML;
var output = { id: 100, rawHTML: body, rawText: rawText };
callback(null, output);
})
.catch(callback);
The problem is with var rawText = body.getElementsByTagName("body")[0].innerHTML;
The error I receive is:
Bargle. We hit an error creating a run javascript. :-( Error:
TypeError: body.getElementsByTagName is not a function eval (eval at (/var/task/index.js:52:23), :16:24) process._tickDomainCallback (node.js:407:9)
Unfortunately - there is no JS DOM API in the Code by Zapier triggers or actions (that is because it isn't run in a browser and doesn't have the necessary libraries installed to fake it).
You might look at Python and instead, and https://docs.python.org/2/library/xml.etree.elementtree.html. Decent question and answer is available here Python Requests package: Handling xml response. Good luck!
Any function not supported by Zapier will result in a TypeError. I needed to use a regular expression to achieve this.

Resources