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.
Related
I'm fairly new to Node, and am wracking my brains on how to achieve the following:
I have a config file that looks something like this:
// various es imports
export default {
input: {
index: 'src/index.ts',
Button: 'src/Button/index.ts',
Spinner: 'src/Spinner/index.ts',
'icons/Notification': 'src/_shared/components/icons/Notification.tsx',
'icons/Heart': 'src/_shared/components/icons/Heart.tsx',
},
//.. other properties
}
From my node script, i need to somehow read this file and do the following:
Delete any entries in the input object that have a key starting
with icons/
Append new entries to the input object.
Write these changes back to the original config file.
Is there a recommended way to do this in Node, i've been looking at a couple of libs, like replace-in-file but none seem to be suited to this particular case.
Just faced the same concern, here is how I solved it :
1. Gets your file content
If it is not a .js file, then use fs.readFileSync (or fs.readFile) like so :
const fs = require('fs');
const path = require('path');
const myObjectAsString = fs.readFileSync(
path.join( process.cwd(), 'my-file.txt' ), // use path.join for cross-platform
'utf-8' // Otherwise you'll get buffer instead of a plain string
);
// process myObjectAsString to get it as something you can manipulate
Here I am using process.cwd(), in case of a CLI app, it will gives you the current working directory path.
If it is a .js file (eg. a JavaScript config file like webpack.config.js for instance), then simply use require native function, as you would do with regular internal file or NPM module, and you will get all module.export content :
const path = require('path');
const myObject = require( path.join( process.cwd(), 'myFile.js') );
2. Modify your object as you want
// ...
myObject.options.foo = 'An awesome option value';
3. Then rewrite it back to the file
You can simply use fs.writeFileSync to achieve that :
// ...
fs.writeFileSync( path.join(process.cwd(), 'my-file.txt', myObject );
If you want to write a plain JavaScript Object, then you can use util.inspect() native method and you may also use fs.appendFileSync :
// ...
// If we wants to adds the 'module.exports = ' part before
fs.writeFileSync( process.cwd() + '/file.js', 'module.exports = ');
// Writes the plain object to the file
fs.appendFileSync( process.cwd() + '/file.js', util.inspect(options));
This is my first electron/node application, I m trying to use a json file as a datastore. so I created a simple one index.json under the app folder next to index.js|css|html
I installed a npm package jsonfile that is loading just fine
When I try to load my json file the EOF is rised claiming that there is no json file, and I can see that using the DevTools source tab that my json file is not there ( not loaded )
I tried force reload from electron app menu.
Here is my files code that is reading my json
const jsonfile = require('jsonfile')
const file = '/index.json';
var json;
jsonfile.readFile(file)
.then(obj => json = obj)
.catch(error => console.error(error))
------------ Edit
correcting the path name to index.json or ./index.json rises the same issue
You can use the native fs (filesystem) module.
let path = "index.json"
const fs = require('fs');
const json = JSON.parse(fs.readFileSync(path));
Thanks for your support
For me the issue was more about file system handling than electron.
All I did is to chmod my project folder to assure that I will be able to read and write into the index.json datastore
sudo chmod -R 777 /opt/workspaces/electron/myElectronPrpjectFolder
Then for a better path resolution I used the basic idea used in electron archtype, It more error safe
const path = require('path')
const file = path.join(__dirname,'index.json');
var json;
var html = "";// The returned object.
$(document).ready(function () {
jsonfile.readFile(file)
.then(obj => {
json = JSON.parse(JSON.stringify(obj));
console.log(JSON.stringify(json))
parseIssues(json.children);
document.getElementById('a').innerHTML = html;
})
.catch(error => console.error(error))
});
You can see that I m using JQuery in this snippet but it also works without JQuery.
in resume, better path resolve policy with granted priveleges on folder.
Thanks
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
I have created a zip file of a .txt file using node.js zlib and while trying to unzip the file i used the same node_module zlib but its throwing error.Please check my code snippet and please feel free to edit code.I also checked the file location its same as the
Error :
Error: unexpected end of file
at Unzip.zlibOnError (zlib.js:153:15)
Code :
const fs=require('fs');
const zlib = require('zlib');
const iii = fs.createReadStream('test.txt.gz');
const oo = fs.createWriteStream('test1.txt');
const unzip = zlib.createUnzip()
iii.pipe(unzip).pipe(oo)
I am unable to understand my mistake.Can anyone help me with the same?
Thanks in advance!!
Used below code to zip the file.
code to zip:
const fs=require('fs');
const zlib = require('zlib');
const gzip = zlib.createGzip();
const inp = fs.createReadStream('test.txt');
const out = fs.createWriteStream('test.txt.gz');
inp.pipe(gzip).pipe(out);
I was getting an error because the file got corrupted while trying the zip-unzip.
There was no error in the code.
So after deleting and recreating zip file, i was able to unzip it.
Note:
Whenever you try something like this,if you get such error, then always check file size it should not be zero. If it is zero,then recreate the zip and try again.
I tried with npm package adm-zip 0.4.4 because the latest one 0.4.7 doesn't work, adm-zip 0.4.4 works on Windows but not on Mac & Linux. Another problem is that I only want zip_folder to be zipped but it zipps the whole directory structure staring from folder_1. This is the code:
var zip = new admZip();
zip.addLocalFolder("./folder_1/folder_2/folder_3/**zip_folder**");
zip.writeZip("./folder_1/folder_2/folder_3/download_folder/zip_folder.zip");
All this happens on the server side. I have searched a lot and tried many npm packages to zip a folder or directory. Any suggestions or any other good approach to solve my problem?
You could also use node-archiver, which was very helpful when I was using it. First you need create an instance of the archiver as follows:
var fs = require('fs');
var archiver = require('archiver');
var archive = archiver.create('zip', {});
var output = fs.createWriteStream(__dirname + '/zip_folder.zip');
This way you tell the archiver to zip the files or folders based on the format you pass along with the method. In this case it's zip. In addition, we create a writeStream which will be piped to the archiver as its output. Also, we use the directory method to append a directory and its files, recursively, given its dirpath:
archive.pipe(output);
archive
.directory(__dirname + '/folder_1/folder_2/folder_3/download_folder/zip_folder')
.finalize();
At the end, we need to finalize the instance which prevents further appending to the archive structure.
Another option is to use the bulk method like so:
archive.bulk([{
expand: true, cwd: './folder_1/folder_2/folder_3/download_folder/zip_folder/',
src: ['**/*']
}]).finalize();
Update 1
A little explanation for the [**/*] syntax: This will recursively include all folders ** and files *.
Try to use the system's zip function:
var execFile = require('child_process').execFile;
execFile('zip', ['-r', '-j', zipName, path], function(err, stdout) {
if(err){
console.log(err);
throw err;
}
console.log('success');
});
Replace zipName and path with what you need.