SyntaxError: Unexpected token { in JSON at position 0 - node.js

I am trying to parse a JSON file but getting an expected token, { at position 0.
SolaceConnetionParser.js
class SolaceConnectionParser {
constructor() { }
//TODO: cannot parse json correctly
parse(filepath) {
const connectionArgs = [];
console.log('File path: ' + filepath);
const rawData = fs.readFileSync(filepath, 'utf-8').toString;
const contents = JSON.parse(rawData);
return contents;
}
}
module.exports = SolaceConnectionParser;
const path = require('path');
const fs = require('fs');
const parser = new SolaceConnectionParser();
const filepath = path.join(__dirname + '../../../configs/test.json');
console.log(parser.parse(filepath));
test.json:
{
"key": "value"
}
Expected:
Rest of statements in code should output to console (i.e.: JSON contents).
Actual:
$ node SolaceConnectionParser.js
File path: C:\Users\u589329\Desktop\angular\dashboard_backend\dashboard_backend\src\configs\test.json
undefined:1
{
^
SyntaxError: Unexpected token in JSON at position 0
at JSON.parse (<anonymous>)
at SolaceConnectionParser.parse (C:\Users\u589329\Desktop\angular\dashboard_backend\dashboard_backend\src\app\solace\SolaceConnectionParser.js:9:31)
at Object.<anonymous> (C:\Users\u589329\Desktop\angular\dashboard_backend\dashboard_backend\src\app\solace\SolaceConnectionParser.js:26:31)
at Module._compile (internal/modules/cjs/loader.js:701:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
at Module.load (internal/modules/cjs/loader.js:600:32)
at tryModuleLoad (internal/modules/cjs/loader.js:539:12)
at Function.Module._load (internal/modules/cjs/loader.js:531:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:754:12)
at startup (internal/bootstrap/node.js:283:19)

JSON objects are represented as Strings and fs.readFileSync() returns a Buffer.
Change
const rawData = fs.readFileSync(filepath, 'utf-8');
to
const rawData = fs.readFileSync(filepath, 'utf-8').toString();
and you should be good to go.

after applying Rob Raisch's answer and also trimming the string, problem was solved.
const rawData = fs.readFileSync(filepath, 'utf-8').toString().trim();

Related

How do I extract a tar file in nodejs using the pipeline() method?

My current code looks like this:
const gzip2 = zlib.createUnzip();
const pack2 = new tar.Unpack();
const source2 = Readable.from('public/img.tar.gz');
const destination2 = fs.createWriteStream('public/images2');
pipeline(source2, gzip2, pack2, destination2, (err) => {
if (err) {
console.error('An error occurred:', err);
process.exitCode = 1;
}
});
But I'm getting this error:
internal/streams/pipeline.js:108
throw new ERR_INVALID_ARG_TYPE(
^
TypeError [ERR_INVALID_ARG_TYPE]: The "val" argument must be an instance of Readable, Iterable, or AsyncIterable. Received an instance of Unpack
at makeAsyncIterable (internal/streams/pipeline.js:108:9)
at pipeline (internal/streams/pipeline.js:265:15)
at Object.<anonymous> (/mnt/c/index.js:39:1)
at Module._compile (internal/modules/cjs/loader.js:1068:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
at Module.load (internal/modules/cjs/loader.js:933:32)
at Function.Module._load (internal/modules/cjs/loader.js:774:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
at internal/main/run_main_module.js:17:47 {
code: 'ERR_INVALID_ARG_TYPE'
}
I've also tried
const pack2 = tar.extract();
without luck.
If anyone can help me to extract this tar file using pipeline, so that I can also unzip the file. I would be very grateful. I've seen people use .pipe(tar.extract()) online, but I'm trying to keep my code as clean and uniform as possible. This: https://www.npmjs.com/package/tar has unfortunately not been very helpful.
const tar = require('tar.gz2')
var read = tar().createReadStream('/public/images');
var write = fs.createWriteStream('compressed.tar.gz');
pipeline(read,write,
(err) => {
if (err) {
throw err
}
})

create gcs storage in node

const functions = require('firebase-functions')
const { Storage } = require('#google-cloud/storage');
let gcs = new Storage ();
const os = require('os');
const path = require('path');
exports.onFileChange = functions.storage.object().onFinalize(event => {
console.log(event);
const bucket = event.bucket;
contentType = event.contentType;
const filePath = event.name;
console.log('file detected')
if(path.basename(filePath).startsWith('renamed-')){
console.log('already renamed this file')
return;
}
const destBucket = gcs.bucket(bucket);
const tmpFilePath = path.join(os.tmpdir(), path.basename(filePath));
const metadata = { contentType : contentType }
return destBucket.file(filePath).download({
destination : tmpFilePath
}).then(() => {
return destBucket.upload(tmpFilePath, {
destination:'renamed-'+ path.basename(filePath),
metadata: metadata
})
})
});
the error is:-
`Function failed on loading user code. Error message: Code in file index.js can't be loaded.
Is there a syntax error in your code?
Detailed stack trace: /srv/node_modules/p-limit/index.js:30
} catch {}
^
SyntaxError: Unexpected token {
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:139:10)
at Module._compile (module.js:617:28)
at Object.Module._extensions..js (module.js:664:10)
at Module.load (module.js:566:32)
at tryModuleLoad (module.js:506:12)
at Function.Module._load (module.js:498:3)
at Module.require (module.js:597:17)
at require (internal/module.js:11:18)
at Object.<anonymous> (/srv/node_modules/#google-cloud/storage/build/src/bucke here t.js:25:16)
`
The error message implies you have a syntax error in your function.
Change the line contentType = event.contentType; to const contentType = event.contentType; and your syntax er

TypeError: notesExist.push is not a function?

i'm just newbie on nodeJs ,and i need your help
my utile.js file :
const fs = require('fs');
const addNotes = function(name,age,birthday){
const notesExist = loadNotes()
notesExist.push({
name: name,
age: age,
birthday:birthday
})
}
const loadNotes = function (){
try{
binaryVersion = fs.readFileSync('./JsonFile/data.json');
stringVersion = binaryVersion.toString();
dataParsed = JSON.parse(stringVersion);
return dataParsed;
}
catch(err){
return [];
}
}
module.exports = {
addNotes: addNotes,
loadNotes: loadNotes
}
my intro.js file
yargs = require('yargs');
const utile = require('./utile.js');
yargs.command({
command: 'add',
describe: 'Adding new record',
builder:{
name:{
describe:'note name',
demandOption:true, // title option to be requires in the command line
type:'string' //requie a string as title value
},
age:{
describe:'note age',
demandOption:true,
type:'string' //require astring as body value
},
birthday:{
describe:'note birthday',
demandOption:true,
type:'string' //require astring as body value
},
},
handler: function(argv){
// console.log(chalk.green(chalk.red(argv.title)))
/* console.log(chalk.green(chalk.green(argv.body))) */
utile.addNotes(argv.name,argv.age,argv.birthday);
}
});
my data.json file :
{"name":"Hannani","age":25,"birthday":1995}
But when i run the intro.js file by : node intro.js add --name="booktitle" --age="dsds" --birthday="1995" i got i nice erro [I spent 3 hours but i didn't find anything to solve that error ]
Error :
/home/simo/Documents/nodeJs/node_modules/yargs/yargs.js:1195
else throw err
^
TypeError: notesExist.push is not a function
at Object.addNotes (/home/simo/Documents/nodeJs/utile.js:34:20)
at Object.handler (/home/simo/Documents/nodeJs/intro.js:56:19)
at Object.runCommand (/home/simo/Documents/nodeJs/node_modules/yargs/lib/command.js:240:40)
at Object.parseArgs [as _parseArgs] (/home/simo/Documents/nodeJs/node_modules/yargs/yargs.js:1107:41)
at Object.parse (/home/simo/Documents/nodeJs/node_modules/yargs/yargs.js:566:25)
at Object.<anonymous> (/home/simo/Documents/nodeJs/intro.js:86:7)
at Module._compile (internal/modules/cjs/loader.js:1151:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
ps: I didn't change anything in my yargs.js file ..
Please what i'm doing wrong ? Thanks in advance !
THe data.json needs to be array format for you to be able to push. Something like this
[{"name":"Hannani","age":25,"birthday":1995}]
Also, since it is a normal json file you could simply require it as will instead of using fs to read it.
const data = require('./JsonFile/data.json')
Hope this helps.

How to add an exception or manage the error at the following node function?

Here is my original code:
function extract_number(conv){
const regex = /(?:(\+?\d{1,3}) )?(?:([\(]?\d+[\)]?)[ -])?(\d{1,5}[\- ]?\d{1,5})/
const result = conv.match(regex)
const value = result[0]
console.log(value);
return value
}
However it is falling with the string does not contains a number to extract
here the example:
extract_number('my number is')
I tried to catch the error as follows:
function extract_number(err,conv){
if (err) {
const regex = /(?:(\+?\d{1,3}) )?(?:([\(]?\d+[\)]?)[ -])?(\d{1,5}[\- ]?\d{1,5})/
const result = conv.match(regex)
const value = result[0]
console.error('There was an error', err);
}
console.log(value)
return value
}
I got:
/home/adolfo/node_js/index.js:61
const result = conv.match(regex)
^
TypeError: Cannot read property 'match' of undefined
at extract_number (/home/adolfo/node_js/index.js:61:29)
at Object.<anonymous> (/home/adolfo/node_js/index.js:69:1)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Function.Module.runMain (module.js:693:10)
at startup (bootstrap_node.js:188:16)
at bootstrap_node.js:609:3
at the seccond function, so I would like to appeciate support with this
Try..catch is your friend
function extract_number(conv){
try{
const regex = /(?:(\+?\d{1,3}) )?(?:([\(]?\d+[\)]?)[ -])?(\d{1,5}[\- ]?\d{1,5})/
const result = conv.match(regex)
const value = result[0]
console.log(value);
return value
}catch(){
return null
}
}
There's different approaches. You can do several checks on result on it's length or if it is type Array, and/or if conv is null or undefined and have that throw your error. Or you can implement a try/catch as specified here, which is probably the easiest way to accomplish what you're trying to do.
function extract_number(conv){
const regex = /(?:(\+?\d{1,3}) )?(?:([\(]?\d+[\)]?)[ -])?(\d{1,5}[\- ]?\d{1,5})/
let value;
try {
const result = conv.match(regex)
value = result[0]
} catch (err) {
console.error('There was an error', err);
}
console.log(value);
return value
}

Load and modify svg files from node.js

We have an API that should send png files. This png files are composition of several svg files and some changes in attributes: background-color, image size..
We are using node.js on the server.
I've tried without success using d3 in order to modify SVG files & Jsdom to use d3 on the backend:
var fs = require('fs');
var d3 = require('d3');
var JSDOM = require('jsdom').JSDOM;
var outputLocation = 'test.svg';
const window = (new JSDOM(`<html><head></head><body></body></html>`, { pretendToBeVisual: true })).window;
window.d3 = d3.select(window.document); //get d3 into the dom
d3.xml("./react02.svg").mimeType("image/svg+xml").get(function(error, xml) {
var importedNode = document.importNode(xml.documentElement, true);
if (error) throw error;
console.log(xml);
window.d3.select('body')
.append('div').attr('class', 'container')
.appendChild(importedNode);
});
fs.writeFileSync(outputLocation, window.d3.select('.container').html()) //using sync to keep the code simple
But I always get an error:
TypeError: Cannot read property 'innerHTML' of null
at Selection.selection_html [as html] (/home/juanda/kk2/node_modules/d3-selection/build/d3-selection.js:793:20)
at Object.<anonymous> (/home/juanda/kk2/test2.js:18:65)
at Module._compile (module.js:624:30)
at Object.Module._extensions..js (module.js:635:10)
at Module.load (module.js:545:32)
at tryModuleLoad (module.js:508:12)
at Function.Module._load (module.js:500:3)
at Function.Module.runMain (module.js:665:10)
at startup (bootstrap_node.js:201:16)
at bootstrap_node.js:626:3
Can't find any example / library reading and modifing svg files on server side.
Moved from d3 to snapsvg as I don't need data analysis, just play with the svg itself.
This is my code:
let {JSDOM} = require('jsdom')
var resolve = require('resolve');
resolve('snapsvg', { basedir: __dirname }, function (err, resource) {
if (err) console.error(err)
else {
const options = {
runScripts: "dangerously",
resources: "usable",
url: "file:///prueba.html" // avoid cors error reading svg file
};
const dom = new JSDOM(`
<!DOCTYPE html><html><body><div id="test"></div></body></html>
`, options);
var script = dom.window.document.createElement('script');
script.src = `file://${resource}`;
var head= dom.window.document.getElementsByTagName('head')[0];
head.appendChild(script);
// console.log(dom.serialize())
script.onload = function () {
// console.log("Script loaded and ready");
// console.log(dom.window)
var s = dom.window.Snap("#test");
dom.window.Snap.load("file:///Users/juandaniel/Code/prueba/2375.svg", onSVGLoaded);
function onSVGLoaded(data) {
s.append(data);
console.log(s.node.innerHTML)
}
};
}
});

Resources