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"));
Related
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
I'm using External Secrets to sync my secrets from azure. And now I need a programmatic way to trigger the sync. With kubectl the command is
kubectl annotate es my-es force-sync=$(date +%s) --overwrite
So, I try to use k8s js sdk to do this. I can success fully get the External Secret
await crdApi.getNamespacedCustomObject("external-secrets.io", "v1beta1", "default", "externalsecrets", "my-es")
However, when I try to update it with patchNamespacedCustomObject, it always tells me "the body of the request was in an unknown format - accepted media types include: application/json-patch+json, application/merge-patch+json, application/apply-patch+yaml"
Here's my code
const kc = new k8s.KubeConfig();
kc.loadFromString(kubeConfig);
const crdApi = kc.makeApiClient(k8s.CustomObjectsApi);
let patch = [{
"op": "replace",
"path": "/metadata/annotations",
"value": {
"force-sync": "1663315075"
}
}];
await crdApi.patchNamespacedCustomObject("external-secrets.io", "v1beta1", "default", "externalsecrets", "my-es", patch);
I am referring their patch example here
const options = {
"headers": {
"Content-type": k8s.PatchUtils.PATCH_FORMAT_JSON_PATCH
}
};
is still required.
I am trying programmatically create a git commit and as part of that I need to create a git tree.
Having read the docs, I am unsure what to send in the request body.
I am able to create a blob and get a sha response but when I try call the create tree endpoint, I get the following:
{
"url": "https://api.github.com/repos/<owner>/<repo>/git/trees/",
"status": 404,
"statusText": "Not Found",
"body": {
"message": "Not Found",
"documentation_url": "https://docs.github.com/rest"
}
}
My code looks like this where I create the blob and then try create the tree:
const blobContent = fs.readFileSync(__dirname + '/../../../templates/main.yaml', { encoding: "utf8" })
const blob = await this.post<IBlobResponse>(`https://api.github.com/repos/${ownerName}/${repoName}/git/blobs`, {
content: blobContent,
encoding: "utf-8"
})
const tree = await this.post(`https://api.github.com/repos/${ownerName}/${repoName}/git/trees/`, {
base_tree: masterRef.object.sha,
tree: [
{
path: "main.yaml",
mode: "100644",
type: "tree",
sha: blob.sha,
content: blobContent
}
]
})
Is the payload for creating the tree correct?
Should path be the local relative path or is it the path that the file will live in inside the repository?
Do I need both the sha and the content?
Is the fact that the content is a yaml file an issue?
Turns out I was including a trailing / in the POST endpoint when creating a tree:
Changed https://api.github.com/repos/${ownerName}/${repoName}/git/trees/ to https://api.github.com/repos/${ownerName}/${repoName}/git/trees and it worked.
Very simple fix but thought I'd share incase anybody else has a similar issue
I am trying to open, read and return an HTML files using Azure functions. I am developing locally and the logs says that the function executed successfully however on the browser I am getting 500 internal server error. Am I doing something wrong in here?
const fs = require('fs');
const path = require('path');
const mime = require('../node_modules/mime-types');
module.exports = function (context, req) {
const staticFilesFolder = 'www/build/';
const defaultPage = 'index.html';
getFile(context, req.query.file);
function getFile(context, file) {
const homeLocation = process.env["HOME"];
if(!file || file == null || file === undefined){
context.done(null,{status:200,body:"<h1>Define a file</h1>",headers:{
"Content-Type":" text/html; charset=utf-8"
}});
}
fs.readFile(path.resolve(path.join(homeLocation, staticFilesFolder, file)),
(err, htmlContent) => {
if (err) {
getFile(context, "404.html");
}
else {
const res = {
status: 200,
body: htmlContent,
headers:{
"Content-Type": mime.lookup(path.join(homeLocation, staticFilesFolder, file))
}
}
context.done(null,res);
}
})
}
};
Note
I am sure that 404.html exists and index.html exists. When I log the contents of htmlContent it is giving the correct output.
functions.json
{
"disabled": false,
"bindings": [
{
"authLevel": "anonymous",
"type": "httpTrigger",
"direction": "in",
"methods":["get"],
"route":"home",
"name": "req"
},
{
"type": "http",
"direction": "out",
"name": "res"
}
]
}
Response on Chrome
If I removed "Content-Length" header the status code changes to 406.
Update 1 The code seems to be running normally on Azure Portal but it is not working when running it locally.
It looks like you are combining two methods of returning data from an http triggered function(context.res and context.done()): https://learn.microsoft.com/en-us/azure/azure-functions/functions-reference-node#accessing-the-request-and-response
Since you are using context.res, try removing context.done();
You are making an incorrect use of context.res, you shouldn't be overwriting it but instead leveraging the methods provided by the Response class provided in the Azure NodeJS worker. If you are using using VSCode you'll get intellisense for these methods. Otherwise see: https://github.com/Azure/azure-functions-nodejs-worker/blob/dev/src/http/Response.ts
Your code should look something like this instead.
context.res.setHeader('content-type', 'text/html; charset=utf-8')
context.res.raw(htmlContent)
Using context.res.raw or context.res.send will already perform the context.done call for you.
Make sure you use content-type=text/html; charset-utf8 instead of content-type=text/html or you'll trigger an issue with the returned content-type. Instead of returning content-type=text/html you end up getting content-type=text/plain which will fail to render your html.
Addressed on: https://github.com/Azure/azure-webjobs-sdk-script/issues/2053
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');