Using a JSON file in JavaScript - javascript

I'm looking to use a JSON file in a Node.js project, but it doesn't seem to be working-
var JsonPath = '../../folderOfjsonFiles';
var JsonFile = JsonPath + 'test.json';
var parseThis = JSON.parse(JsonFile);
console.dir(parseThis);
Any suggestions as to what I'm doing wrong? Running this yields this error:
"test1": {
^
uncaught: SyntaxError: Unexpected token :
at Module._compile (module.js:399:25)
at Object..js (module.js:410:10)
at Module.load (module.js:336:31)
at Function._load (module.js:297:12)
at require (module.js:348:19)
Where test1 is the first JSON object in my file.
This is my JSON file-
{
"test1": {
"testname": "alpha",
"password": "password"
}
}
Even before the JSON parsing, how do I read from a file that I will store locally on the server-side? I feel like I'm overcomplicating this.

A JSON object has to be included in {} or [] at top level, so you cant do
"test1": {...},
"test2": {...}
Use
{
"test1": {...},
"test2": {...}
}
instead.

I store my Express server config in a file and read it like this:
var fs = require('fs');
var path = require('path');
var conf = fs.readFileSync(path.join(__dirname, './config.json'), 'utf8');

Related

how to update name with variable in nodejs?

I have dummy template of package.json . I want to copy dummy package.json inside some folder (Application name folder) and update the name from from package.json . can we do this in node js.
here is my source package.json file
{
"name":"$name"
}
I tried like this
const fs = require('fs');
const prompt = require('prompt-sync')();
let appName = prompt('what is application name..?');
if(!appName){
appName='temp'
}
console.log(`Application name is ${appName}`);
if (!fs.existsSync(`${appName}`)){
fs.mkdirSync(`${appName}`);
}
fs.copyFile('./source/package.json', `${appName}/package.json`, (err) => {
if (err) throw err;
console.log('source.txt was copied to destination.txt');
});
when I run node index.js . it ask "application name" user enter application name let say example (abc). It create a folder abc and put package.json file which is working fine.
Now issue is I want the content of package.json is
{
"name":"abc"
}
can we replace the name variable ?
Let's say you have ./abc/package.json and its contents look like this:
{
"name": "$name",
"version": "0.1.0"
}
If you want to modify just the name field, you'll have to:
read the package data as JSON text
parse it as an object
modify the name property to your desired value
write it back to the file
A minimal example of doing that in a script might look like this:
./rename.mjs:
import {readFile, writeFile} from 'node:fs/promises';
const pkgPath = './abc/package.json';
const textEncoding = {encoding: 'utf-8'};
const json = await readFile(pkgPath, textEncoding);
const pkgData = JSON.parse(json);
pkgData.name = 'abc';
const prettyJson = JSON.stringify(pkgData, null, 2);
await writeFile(pkgPath, prettyJson, textEncoding);
After you run it:
node rename.mjs
The package contents will be updated:
{
"name": "abc",
"version": "0.1.0"
}
Ref:
fsPromises.readFile
fsPromises.writeFile

Using Puppeteer&Python on Node.JS to solve captchas

I'm using puppeteer library to access some sites and leach data from their HTML files. for that manner, I've got a Python script that should help me solve each captcha if there is.
now, to run the Python script, I'm using python-shell from npm, and committing this:
let options = {
mode: 'text',
args: [captchas[0].sitekey],
scriptPath: path.resolve('bypass'),
pythonPath: '/usr/bin/python',
}
console.log(`options.scriptPath`, options.scriptPath)
PythonShell.run(
`bypass/bypass.py`,
options,
(err, [, captchaKey]) => {
if (err) throw err
let solutions = [
{
_vendor: captchas[0]._vendor,
id: captchas[0].id,
text: captchaKey,
hasSolution: true,
},
]
resolve({ solutions })
}
)
I've got this error -
Solving captcha...
options.scriptPath MY_PATH/backend/bypass
file:///MY_PATH/backend/bypass/captchaBypasser.js:18
(err, [, captchaKey]) => {
^
TypeError: object null is not iterable (cannot read property Symbol(Symbol.iterator))
at file:///MY_PATH/backend/bypass/captchaBypasser.js:18
at PythonShell._endCallback (/MY_PATH/backend/node_modules/python-shell/index.js:254:20)
at terminateIfNeeded (/MY_PATH/backend/node_modules/python-shell/index.js:209:39)
at ChildProcess.<anonymous> (/MY_PATH/backend/node_modules/python-shell/index.js:182:13)
I've tried also to use spawn of child_process, like this:
const location = path.resolve('bypass/bypass.py')
console.log(`python ${location} ${captchas[0].sitekey}`)
const run = spawn('python', [location, captchas[0].sitekey])
run.stdout.on('data', ([, captchaKey]) => {
let solutions = [
{
_vendor: captchas[0]._vendor,
id: captchas[0].id,
text: captchaKey,
hasSolution: true,
},
]
resolve({ solutions })
})
and it appears to just crush without even an outcome.
So I've tried to try the actual command line:
python /MY_PATH/backend/bypass/bypass.py ae7317...TOKEN...d0dab8b75
BY THE WAY - I've TRYED ALSO python3 WITH VERSION 3.10.0
And now I've got this error:
from hcapbypass import bypass
File "/MY_PATH/backend/bypass/hcapbypass.py", line 35
def N_Data(req) -> str:
^
So I tried to use the latest version of Python, 3.10.0, that came out like a few weeks ago, and that's the outcome:
File "/MY_PATH/backend/bypass/bypass.py", line 4, in <module>
captcha_solved = bypass(sys.argv[1], 'google.com', True)
TypeError: bypass() missing 1 required positional argument: 's'
For your full understanding, here is the bypass and the solver codes:
bypass.py
from hcapbypass import bypass
import sys
captcha_solved = bypass(sys.argv[1], 'google.com', True)
print(captcha_solved)
hcapbypass
Link to github
Does anyone know what to do?
Thanks a lot!!!
OK, ive got the solution:
inside the hcapbypass.py file, the httpx module isn't presented, so I've created an environment with bin & lib folders to install it locally.
In addition, few functions got an argument that doesn't exist.
And of course, destructuring an array that is null / undefined - throws an error!

Evaluating module.exports in Ruby (Rails)

Currently I'm looking to try to get something in a Hash format in Ruby from JS.
I have a JS module that looks something like this
module.exports = {
key1: "val",
key2: {
key3: "val3"
}
...
}
This is given to me as just one string. I'm aware that ExecJS could be helpful here but I'm not sure what the best way to convert it to a Hash would be.
I'm currently trying to do something like this
contents.prepend("var module = {exports: {}};\n")
context = ExecJS.compile contents
context.eval('module.exports').to_hash
But when giving it a string like above I'm getting a parsing error from the JSON gem.
I just tried putting this in a script and running it:
require 'execjs'
str = <<-JS
// Note, you could just do `var module = {}` here
var module = {exports: {}};
module.exports = {
key1: "val",
key2: {
key3: "val3"
}
}
JS
context = ExecJS.compile str
puts context.eval('module.exports').to_hash
# => {"key1"=>"val", "key2"=>{"key3"=>"val3"}}
Maybe you're getting the JSON parse error because the module contains something which can't be serialized.
Here's another approach.
Make a JS file which loads the module and exports it as JSON.
var fs = require('fs');
var hash = require('path/to/my_module.js');
fs.writeFileSync('path/to/output.json', JSON.stringify(hash), 'utf8');
Run that with nodejs my_script.js then read it from Ruby:
require 'json'
hash = JSON.parse "path/to/output.json"
If the problem is the runtime, you can use mini_racer as the runtime used by ExecJS. Just include the gem:
gem 'execjs'
gem 'mini_racer'
Then you can run:
p ExecJS.runtime
# > #<ExecJS::MiniRacerRuntime:0x00007fc44ea20bd8>
Then you would setup the context first:
require 'execjs'
jscode = <<-JS
module.exports = {
key1: "val",
key2: {
key3: "val3"
}
}
JS
context = ExecJS.compile "var module = {};"
result_hash = context.eval jscode
puts result_hash["key1"]

JavaScript get object from json file

Im new to js and i dont understand how can i take an object from json file,
for example this file : local.json
{
"server": "myname",
"url": 10.0.0.1
}
I need to get the url to insert in in my js code like this, replace the 127.0.0.1 with what i have in json file at url:
import axios from 'axios';
import jsonFile from '../local.json';
const http = require("http");
const host = '127.0.0.1'; #should be 10.0.0.1 from json file
Your json file should be:
{
"server": "myname",
"url": "10.0.0.1"
}
(use double quotes)
and just use dot:
const host = jsonFile.url
In javascript, Specific Object value can be accessed by following three ways:
DOT (.) operator
const obj = {
"server": "myname",
"url": "10.0.0.1"
};
const url = obj.url;
console.log(url); // 10.0.0.1
Square bracket ([])
const obj = {
"server": "myname",
"url": "10.0.0.1"
};
const url = obj["url"];
console.log(url); // 10.0.0.1
De-structuring (>=ES6)
const obj = {
"server": "myname",
"url": "10.0.0.1"
};
const { url } = obj;
console.log(url); // 10.0.0.1
You need to use the "dot" syntax.
const host = jsonFile.url
I assume you need to get configurations to instantiate your server.
You may like to follow below steps to instantiate settings:
Install the dependency config
It allows you to define a json file of settings.
I define the structure
you create a directory inside your project called config inside you create a json file default.json
│
config
│--- default.json
│
inside the file you write your values
{
   "server": "myname",
   "url": "10.0.0.1"
}
and to access you do the following
file = index.js
const config = require ("config");
console.log (config.get ("url"));

TypeScript error cannot use 'in' operator to search for '_id' for typescript and pouchdb

I'm using pouchDb with Angular2 in a typescript environment with webstorm and systemjs. In the editor, it appears I have sufficent configuration to where I can get intellisense and pouchDB does run.
I have this test code.
var mydb = new PouchDB('TestDb');
var myObj = {"_id" : "1", "description":"hello world"} ;
var objAsString = JSON.stringify(myObj) ;
mydb.put(objAsString).then(function (response) {
// handle response
console.log("save to db:" + response) ;
}).catch(function (err) {
console.log(err);
});
I get the following error
TypeError: Cannot use 'in' operator to search for '_id' in {"_id":null,"description":"hello world"}
at PouchDB.<anonymous> (http://localhost:63342/clipsalive/node_modules/pouchdb/dist/pouchdb.js:210:21)
at PouchDB.<anonymous> (http://localhost:63342/clipsalive/node_modules/pouchdb/dist/pouchdb.js:11043:18)
at PouchDB.<anonymous> (http://localhost:63342/clipsalive/node_modules/pouchdb/dist/pouchdb.js:5996:21)
at PouchDB.<anonymous> (http://localhost:63342/clipsalive/node_modules/pouchdb/dist/pouchdb.js:11043:18)
at http://localhost:63342/clipsalive/node_modules/pouchdb/dist/pouchdb.js:8252:21
at lib$es6$promise$$internal$$initializePromise (http://localhost:63342/clipsalive/node_modules/angular2/bundles/angular2-polyfills.js:1558:9)
at new lib$es6$promise$promise$$Promise (http://localhost:63342/clipsalive/node_modules/angular2/bundles/angular2-polyfills.js:1849:9)
at PouchDB.<anonymous> (http://localhost:63342/clipsalive/node_modules/pouchdb/dist/pouchdb.js:8239:19)
at PouchDB.put (http://localhost:63342/clipsalive/node_modules/pouchdb/dist/pouchdb.js:11043:18)
at http://localhost:63342/clipsalive/node_modules/pouchdb/dist/pouchdb.js:5991:32
I'm thinking it has to do with module loading, I've tried it with an without a value for _id with same result.
Is this a module loading problem and how do I resolve it?
The put method in PouchDb expects a JSON object not a string.
You should just send the object without stringifying it.
var myObj = {"_id" : "1", "description":"hello world"} ;
mydb.put(myObj)

Categories