The program prints perfectly when there is no License Plate in the frame, but when there is, I get the SyntaxError. Node.js and OpenALPR is installed. Photos are successfully being taken also.
const PiCamera = require('pi-camera');
function getRandomInt(max) {
return Math.floor(Math.random() * Math.floor(max));
}
setInterval(function() {
var path = './' + getRandomInt(500) + '.jpg';
const myCamera = new PiCamera({
mode: 'photo',
output: path,
width: 1920,
height: 1080,
nopreview: false,
});
myCamera.snap()
.then((result) => {
var exec = require('child_process').exec;
var cmd = 'alpr -c eu -n 1 --json ' + path;
exec(cmd, function(error, stdout, stderr) {
var data = JSON.parse(stdout);
if (data.results.length > 0) {
console.log(data.results[0].plate);
} else {
console.log("\n\n\nNo license plate found.\n\n");
}
});
console.log(result);
})
.catch((error) => {
console.log(error);
});
}, 2e3);
The error and where it occurs is:
undefined:1
SyntaxError: Unexpected end of JSON input
at JSON.parse (<anonymous>)
at /home/pi/Project/project.js:28:33
at ChildProcess.exithandler (child_process.js:301:5)
at ChildProcess.emit (events.js:189:13)
at maybeClose (internal/child_process.js:970:16)
at Socket.stream.socket.on (internal/child_process.js:389:11)
at Socket.emit (events.js:189:13)
at Pipe._handle.close (net.js:600:12)
Output of console.log(stdout); before var data declaration:
{"version":2,"data_type":"alpr_results","epoch_time":1588355061888,"img_width":1920,"img_height":1080,"processing_time_ms":1447.340698,"regions_of_interest":[],"results":[]}
There is a space at the end of the JSON.
try {
var data = JSON.parse(stdout.trim())
} catch (e) {
console.error('Failed to Parse JSON!', e)
}
Related
i'm far to be an expert in js, so be indulgeous.
i'm trying to write a script in js for opening several connection (10 here) from one server to another one via telnet protocol.
Here is my script :
const {
readFileSync
} = require('fs');
//const { Client } = require('telnet-client');
const {
Telnet
} = require('telnet-client');
const conn = (nb) => {
const conn = new Telnet();
conn.on('ready', () => {
console.log(`[${nb}]`, 'Client :: ready');
conn.shell((err, stream) => {
if (err) {
console.log(err);
throw err;
}
stream.on('close', () => {
console.log(`${nb}`, 'Stream :: close');
conn.end();
}).on('data', (data) => {
console.log(`${nb}`, "OUTPUT: " + data);
});
stream.end('sleep 600\n');
});
}).connect({
host: 'srvAP',
port: 23,
username: 'toto',
password: 'toto'
});
}
Array.from(Array(10)).forEach(async(x, nb) => {
let now = Date.now();
setTimeout(function() {
console.log("Sleep ", nb);
console.log(`${nb}`, "Run conn " + nb);
conn(nb);
console.log("Sleep end ", nb, Date.now() - now);
}, nb * 750);
});
When i launch it i have some errors :
/exploit/tmp/SLE/poc_vega-ssh-load/node_modules/telnet-client/lib/index.js:130
return reject(new Error('Cannot connect'));
^
Error: Cannot connect
at Socket.<anonymous> (/exploit/tmp/SLE/poc_vega-ssh-load/node_modules/telnet-client/lib/index.js:130:35)
at Object.onceWrapper (node:events:627:28)
at Socket.emit (node:events:513:28)
at Socket._onTimeout (node:net:550:8)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)
Do you have an idea or for correcting this error, or for helping me writing a (more) simple script to do what i want?
I have
fileUploadPath="d:/downloads";
and
entry.name='155ce0e4-d763-4153-909a-407dc4e328d0/63690689-e183-46ae-abbe-bb4ba5507f1a_MULTI_0_3/output/res2/res2.fcs';
when try to create res2.fcs file with following above path it shows gives me error, why it is not creating the folder structure?
code:
data.entries.forEach(entry => {
console.log(entry.name);
if (fs.existsSync(fileUploadPath)) {
var sourceFilePath = fileUploadPath + '/' + entry.name;
if (!fs.existsSync(sourceFilePath)) {
fs.mkdir(sourceFilePath, {recursive: true }, (err) => {if (err) {
console.log("Failed :" + err);
} else {
const fstream = fs.createWriteStream(require('path').format({dir: fileUploadPath, base: entry.name })); fstream.write('fileContent');
fstream.end();
fstream.on("finish", f => {
console.log(f)
});
fstream.on("error", e => {
console.log(e)
});
}
});
} else {
console.log('d');
}
} else {
console.log('ssss')
}
})
error:
[Error: ENOENT: no such file or directory, open 'D:\downloads\626a69d18d2468c5082fc6e1\MULTI_1_2022-04-28_11-00-38\output\res1\res1.fcs'] {
errno: -4058,
code: 'ENOENT',
syscall: 'open',
path: 'D:\\downloads\\626a69d18d2468c5082fc6e1\\MULTI__2022-04-28_11-00-38\\output\\res1\\res1.fcs'
you're passing file path to .mkdir instead of folder, so you should first create a folder, and then write the file
(as you're creating a folder that has the same name as the file, you should've got EISDIR error, instead of this one, which also says the file write didn't work)
use path.dirname to extract folder and pass it to .mkdir:
// require path module at the top of the script
const path = require('path');
fs.mkdir(path.dirname(sourceFilePath), { recursive: true }, (err) => {
//...
Trying to SSH to a server and able to. However, when I try to run sudo command it prompts me to enter the password of the userid mentioned. How do I prevent any keyboard interruption and hardcode the password so it doesn't prompt for password.
server.js
const { Client } = require('ssh2');
const conn = new Client();
conn.on('ready', () => {
console.log('Client :: ready');
conn.exec('sudo ls -lrt',{ stdin: 'password\n', pty: true }, (err, stream) => {
if (err) throw err;
stream.on('close', (code, signal) => {
console.log('Stream :: close :: code: ' + code + ', signal: ' + signal);
conn.end();
}).on('data', (data) => {
console.log('STDOUT: ' + data);
}).stderr.on('data', (data) => {
console.log('STDERR: ' + data);
});
});
}).connect({
host: 'hostname',
port: 22,
username: 'user1',
password: 'password'
});
The prompt I get:
STDOUT: [sudo] password for user1:
STDOUT:
sudo: timed out reading password
The below code works for me.
const Client = require('ssh2').Client;
const conn = new Client();
const encode = 'utf8';
const connection = {
host: 'hostname.foo.com',
username: 'iamgroot',
password: 'root#1234'
}
conn.on('ready', function() {
// Avoid the use of console.log due to it adds a new line at the end of
// the message
process.stdout.write('Connection has been established');
let password = 'root#1234';
let command = '';
let pwSent = false;
let su = false;
let commands = [
`ls -lrt`,
`sudo su - root`,
`ls -lrt`
];
conn.shell((err, stream) => {
if (err) {
console.log(err);
}
stream.on('exit', function (code) {
process.stdout.write('Connection closed');
conn.end();
});
stream.on('data', function(data) {
process.stdout.write(data.toString(encode));
// Handles sudo su - root password prompt
if (command.indexOf('sudo su - root') !== -1 && !pwSent) {
if (command.indexOf('sudo su - root') > -1) {
su = true;
}
if (data.indexOf(':') >= data.length - 2) {
pwSent = true;
stream.write(password + '\n');
}
} else {
// Detect the right condition to send the next command
let dataLength = data.length > 2;
let commonCommand = data.indexOf('$') >= data.length - 2;
let suCommand = data.indexOf('#') >= data.length - 2;
console.log(dataLength);
console.log(commonCommand);
console.log(suCommand);
if (dataLength && (commonCommand || suCommand )) {
if (commands.length > 0) {
command = commands.shift();
stream.write(command + '\n');
} else {
// su requires two exit commands to close the session
if (su) {
su = false;
stream.write('exit\n');
} else {
stream.end('exit\n');
}
}
}
}
});
// First command
command = commands.shift();
stream.write(command + '\n');
});
}).connect(connection);
I have this straightforward node project, with a main.js file when I run it locally node main.js it works fine. But when I do an npm install -g cli-tweet and then try to run it, it outputs this error :
/home/USER/.npm-global/bin/tweet: 1: /home/USER/.npm-global/bin/tweet: Syntax error: "(" unexpected
The package.json looks something like this :
{
"name": "cli-tweet",
"main": "main.js",
"bin": {
"tweet": "main.js"
},
[...]
}
Any idea on how to fix this ?
Edit 1:
The code for main.js
var OAuth = require('oauth').OAuth,
colors = require('colors'),
Twitter = require('twitter'),
fs = require('fs'),
get_args = require('cli-pipe');
var CONFIG_FILE = '.tweet.json',
REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token',
ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token',
OAUTH_VERSION = '1.0', HASH_VERSION = 'HMAC-SHA1';
var key = "XYZ",
secret = "XYZ", tweetText;
function getAccessToken(oa, oauth_token, oauth_token_secret, pin) {
oa.getOAuthAccessToken(oauth_token, oauth_token_secret, pin,
function (error, oauth_access_token, oauth_access_token_secret, results2) {
if (error && parseInt(error.statusCode) == 401) {
throw new Error('The pin number you have entered is incorrect'.bold.red);
}
var keys = {
'ACCESS_TOKEN_KEY': oauth_access_token,
'ACCESS_TOKEN_SECRET': oauth_access_token_secret
};
fs.open(CONFIG_FILE, "wx", function (err, fd) {
try {
fs.close(fd, function (err) {
});
} catch (e) {
}
});
fs.writeFileSync(CONFIG_FILE, JSON.stringify(keys));
console.log('Try echo "test" | cli-tweet'.cyan);
process.exit(1);
});
}
function getRequestToken(oa) {
oa.getOAuthRequestToken(function (error, oauth_token, oauth_token_secret, results) {
if (error) {
throw new Error(([error.statusCode, error.data].join(': ')).bold.red);
} else {
console.log(('https://twitter.com/oauth/authorize?oauth_token=' + oauth_token).underline.blue)
console.log('Enter the pin number here:'.bold.yellow);
var stdin = process.openStdin();
stdin.on('data', function (chunk) {
var pin = chunk.toString().trim();
getAccessToken(oa, oauth_token, oauth_token_secret, pin);
});
}
});
}
function tweet(userTokens) {
var client = new Twitter({
consumer_key: key,
consumer_secret: secret,
access_token_key: userTokens.oauth_access_token,
access_token_secret: userTokens.oauth_access_token_secret
});
console.log("Tweet :" + tweetText.bold.cyan);
if (tweetText.length > 0) {
client.post('statuses/update', {status: tweetText}, function (error, tweet, response) {
if (error) {
console.log("Error :" + JSON.stringify(error));
}
process.exit(1);
});
} else {
console.log("Pipe a tweet".bold.red);
}
}
var isConfig = process.argv[2];
if (isConfig === undefined || isConfig.toLowerCase() != "config") {
try {
var contents = fs.readFileSync(CONFIG_FILE).toString(), tokens = JSON.parse(contents);
} catch (e) {
console.log("Error: Try running 'tweet config' command".bold.red);
}
if (tokens != undefined && (tokens.ACCESS_TOKEN_KEY != undefined && tokens.ACCESS_TOKEN_SECRET != undefined)) {
try {
get_args(function (args) {
tweetText = args[2];
tweet({
"oauth_access_token": tokens.ACCESS_TOKEN_KEY,
"oauth_access_token_secret": tokens.ACCESS_TOKEN_SECRET
});
});
} catch (e) {
console.log("Error: Unexpected error while tweeting".bold.red);
}
} else {
console.log("Try running 'cli-tweet config' command".bold.red);
}
} else {
var oa = new OAuth(REQUEST_TOKEN_URL, ACCESS_TOKEN_URL, key, secret, OAUTH_VERSION, 'oob', HASH_VERSION);
getRequestToken(oa);
}
Edit 2 :
Running the code like this: node /home/USER/.npm-global/lib/node_modules/cli-tweet/main.js seems to work
1) Add folder bin
2) Add file bin/tweet with
#!/usr/bin/env node
require('../main.js');
3) change package.json
"bin": {
"tweet": "./bin/tweet",
}
I need some help trying to stop node from throwing this error, or at-least understand why I can't seem to be able to catch it:
events.js:72
throw er; // Unhandled 'error' event
^
Error: socket hang up
at SecurePair.error (tls.js:999:23)
at EncryptedStream.CryptoStream._done (tls.js:695:22)
at CleartextStream.read [as _read] (tls.js:496:24)
at CleartextStream.Readable.read (_stream_readable.js:320:10)
at EncryptedStream.onCryptoStreamFinish (tls.js:301:47)
at EncryptedStream.g (events.js:175:14)
at EncryptedStream.EventEmitter.emit (events.js:117:20)
at finishMaybe (_stream_writable.js:354:12)
at endWritable (_stream_writable.js:361:3)
at EncryptedStream.Writable.end (_stream_writable.js:339:5)
at EncryptedStream.CryptoStream.end (tls.js:633:31)
at Socket.onend (_stream_readable.js:483:10)
This is the code snippet that causes the error:
var req = https.request(options, function(res) {
res.setEncoding('utf8');
var buffer = '';
res.on('data', function(data) {
buffer += data;
});
res.on('end', function() {
try {
var json = JSON.parse(buffer);
} catch (err) {
return callback(err);
}
callback(null, json);
});
});
req.on('error', function(err) {
callback(err);
});
req.end(data);
api.prototype._get = function(action, callback, args) {
args = _.compactObject(args);
var path = '/api/' + action + '/?' + querystring.stringify(args);
this._request('get', path, undefined, callback, args)
}
api.prototype._post = function(action, callback, args) {
var path = '/api/' + action + '/';
args = _.compactObject(args);
var data = querystring.stringify(args);
this._request('post', path, data, callback, args);
}
Why isn't req.on('error' catching this err?
Node version: 0.10.21
You're missing an error-handler for the response.
res.on('error', function errorHandler(err) { console.log(err); });