How to make and reference a configuration file in javascript - javascript

I have a file that I am trying to make a config.json file for to be able to input and change the data quick and easily. The code below is my mention.js file that I mapped and referenced into my index.js File. The data below needs to be changed periodically and and a config file that I can set the 1. accountName and 2. userId Into my mention.js file. I’m new to npm and JavaScript and am still learning so any help and advice would be extremely helpful. Thank you!!
const map = new Map();
map.set("Pogo0303PTA",'<#679533427925450852>');
map.set("Wretched0671pta", "<#679533427925450852>");
map.set("Pogo0347PTA", "<#679533427925450852>");
map.set("Wretched0047pta", "<#679533427925450852>");
map.set("PogoDroid","<#679533427925450852>");
module.exports = map;```
```{
"acct1": "pogopta000",
"userid1": "65465132168451324"
},
{
"acct2": {account}
"userid2": {userID}
} ETC...

If you only need to read the config.json file once, you can use const config = require('./config.json'), assuming you have the .js file in the same folder as config.json.
If you need to read config.json you can use node's built in module fs by putting const fs = require('fs') at the top of your program and using let config = JSON.parse(fs.readFileSync('./config.json')) to read the file, and using fs.writeFileSync('./config.json', JSON.stringify(config)) to write the file.
You can structure your json file like:
[
{
"accountName": "Pogo0303PTA",
"userId": "<#679533427925450852>"
},
{
"accountName": "Wretched0671pta",
"userId": "<#679533427925450852>"
},
etc...
]
Hope this helped!

Related

Parse INI file in Node.js

I build a Node.js tool in order to change GCP config quickly. But I'm a bit stuck on the parsing of the config_nameOfConfig file.
It looks like this :
[core]
account = email#example.fr
project = project-example
disable_usage_reporting = False
[compute]
region = europe-west1-b
(This file is available in '/Users/nameOfUser/.config/gcloud')
And I want to convert it in an object like this :
const config = {
account:"email#example.fr",
project:"project-example",
disable_usage_reporting:false,
region:"europe-west1-b",
};
I get the content of this file with the fs.readFileSync function who converts it into a string.
An idea ?
This seems to be an ini file format. Unless you want to do the parsing yourself, you'd better just download a library to your project, for example:
npm install ini
Then in the code:
var ini = require('ini')
var fs = require('fs')
var config = ini.parse(fs.readFileSync('./config_nameOfConfig', 'utf-8'))
In config you should now have object containing the data in the file.
You can console.log(config) to see how it exactly looks like.

Go back in directory in node.js (fs.readFileSync)

I'm renewing my discord.js bot folder hirarchy. To make in more structured I made a folder "src" with all js-files. Now if I want to readFileSync a json file outside the src-folder, I can't figure out how to do it.
Lets imagine this Folder:
Folder {
src {
commands {
ping.js
}
main.js
}
config1.json
database {
config2.json
}
}
I use this command to read a json file:
const config1 = JSON.parse(fs.readFileSync("____config1.json", "utf-8"));
const config2 = JSON.parse(fs.readFileSync("____config2.json", "utf-8"));
I hope my folder illustration was clear. Can someone help me how to access both of those files? The underscores are the missing characters
Thanks in advance!
Just like how you could use cd .. to navigate back a directory, you can do the same with fs.
const config1 = JSON.parse(fs.readFileSync("../config1.json", "utf-8"));
const config2 = JSON.parse(fs.readFileSync("../database/config2.json", "utf-8"));
../config1.json and ../database/config2.json

React Native read yaml file

I'd like to read and parse a static yaml resource file (let's starts from there) within my React Native source code, I tried require('path/to/file.yaml') to no avail.
I also tried with npm's libraries such as read-yaml or yaml-loader all of which cannot get the yaml content properly.
It is a breeze with json file, I can just `require('path/to/file.json') and immediately get everything in nice object format.
Is there a way to read yaml in react native? It is just another text file right with a different format right, so I don't think it will be that hard to read and parse the yaml file., but I am new to JavaScript and React-Native here coming from C/C++ background
Since there appears to be no built-in support for yaml, I believe you would need to use something like react-native-fs, or in Expo FileSystem.readAsStringAsync (treating the file as an asset). You should then be able to use a library such as yaml-js to parse the string as read.
You can't use require directly to load yaml.
If you're using Expo:
use a hook:
const [assets, assetsLoadError] = useAssets([
require(uri)
]);
load asset (won't work without the hook above):
const loadedAsset = await Asset.loadAsync(
require(uri)
);
Read the file into a string var:
let content;
try {
content = await FileSystem.readAsStringAsync(
loadedAsset.localUri
);
} catch (e) {
console.log({ e });
}
Parse YAML from string, e.g. with YAML npm package:
const parsedYAML = YAML.parse(content);
First install
npm install --save babel-plugin-content-transformer
Then add to your babel config :
plugins: [
[
'content-transformer',
{
transformers: [
{
file: /\.ya?ml$/,
format: 'yaml',
},
],
},
],
],

How to get json values using nodejs

I am trying to get json values using nodejs but not working.I have searched some question in stackoverflow related this but always I am getting [Object Object] like this.I do not know Why I am getting like this.Anyone can resolve this issue?
file.json:
{
"scripts": {
"mr": "place",
"kg": "time",
"bh": "sec"
}
}
extension.js:
var fs = require("fs");
var file = JSON.parse(fs.readFileSync("c:\\xampp\\htdocs\\projects\\file.json", "utf8"));
console.log(file);
This is not duplicate. I have tried many ways but not working.
Note:I am using this code inside my visual studio code extension.
In node, you can import JSON like a JavaScript file
const file = require('./file.json')
console.log(file)
See is there a require for json in node.js for more info
const data = require("./file.json")
console.log(data.scripts)
Try this one out it is simple.
const fs = require('fs');
const paht = require('path');
console.log(paht.join(__dirname,'../file.json'));
let file = JSON.parse(fs.readFileSync(paht.join(__dirname,'../file.json'), "utf8"));
__dirname gives you the directory of your current file, I used path.join to make sure I can go further.
I put the json file in upper directory in my case

Saving files locally with electron

I have some template files that contain a few variable strings each, I'd like to build a very simple input form with Electron (https://www.electronjs.org/) and I want to save the composed output file on the user's computer.
Is there any module I can use to let Electron save files locally?
If you are targeting multiple platforms, I answered a similar question here. Basically app.getPath(name), app.setPath(name, path), and app.getAppPath() are very useful in saving files to the the right place regardless of the OS.
You may also want to check out these Nodejs packages which help simplify saving files directly to the host machine...
fs-jetpack
graceful-fs
Node.js fs
If you intend for users to save files you might also have a look at the Dialog api where you can specifically invoke a save dialog for that purpose.
A sample code is :
const fs = require('fs');
try { fs.writeFileSync('myfile.txt', 'the text to write in the file', 'utf-8'); }
catch(e) { alert('Failed to save the file !'); }
You can of course store the file's name as well as the content's name in variables.
This will save the content in myfile.txt, which is located inside the current working directory (which you can get through process.cwd()). If you want to write, let's say in the user's home directory, you can use the app.getPath function.
const {dialog} = require('electron').remote;
var fs = require('fs');
export default {
methods: {
save: function () {
var options = {
title: "Save file",
defaultPath : "my_filename",
buttonLabel : "Save",
filters :[
{name: 'txt', extensions: ['txt']},
{name: 'All Files', extensions: ['*']}
]
};
dialog.showSaveDialog(null, options).then(({ filePath }) => {
fs.writeFileSync(filePath, "hello world", 'utf-8');
});
},
}
}

Categories