I'm using Node.js and I'm having trouble figuring out how could I read a YAML file, replace a value in it, and write the updated value to the YAML file.
I'm currently using the module "yamljs" which allows me to load the YAML file and I've managed to edit the value in the loaded Object.
The only part I need help with, is how to write to the YAML file.
Cause for some reason, I can't find the solution for that anywhere, and I'm not even sure if I could use the module for that.
The module does have some command line tools, but I'm not too sure how to use those either.
The module "js-yaml" worked for my case. https://github.com/nodeca/js-yaml
Here's the code I used:
const yaml = require('js-yaml');
...
let doc = yaml.safeLoad(fs.readFileSync('./Settings.yml', 'utf8'));
doc.General.Greeting = newGreet;
fs.writeFile('./Settings.yml', yaml.safeDump(doc), (err) => {
if (err) {
console.log(err);
}
});
Related
first, I want to upload .xlxs and .csv file in node.js. then I want to read this file, edit this file, and also want to save this file in mongoose schema in the database.
and I am new in node.js and I want to learn node backend
please guide me, how I can do this and is this possible?
Reading and writing files in node uses the fs module. Its already included in core node so simply include it
const fs = require('fs')
// synchronous version that will wait until the whole file is read
let file_data = fs.readFileSync('/file/path/file.csv' , 'utf-8')
// async version
fs.readFile('/file/path/file.csv' , 'utf-8', (err, file_data) => {
if (err)
console.error(err)
else
console.info(file_data)
// file_data is your data as string
})
If you specifically need to read and edit csv/xlsx you'll need to browse NPM for packages that help out with that.
You can do it easily by using sheetjs
See this example : https://github.com/SheetJS/sheetjs/tree/master/demos/server
I'm trying to build a nodeJS tool to help me analyzing another AngularJS source code.
The idea is to :
read some of the angular project javascript files
for each file, grab the content
eval the content from the file
do some stuff
The problem I'm facing is that my Angular source code uses es6 features like import, export, arrow functions, ...Etc. and I using nodeJS which does not support these features yet.
So I tried to use #babel/core transform() from my Node app code, but it doesn't work. I keep getting error like Unexpected identifier which means it doesn't understand the import {stuff} from 'here'; syntaxe.
srcFiles.forEach(content => {
try {
(function() {
eval(require("#babel/core").transform(content.text).code)
}.call(window, angular));
} catch (e) {
console.log(e);
}
});
An sample test file :
import _ from 'loadash';
console.log("I'm a file with import and export");
export const = 42;
Any idea how I can get this stuff working ? Or maybe another approach ?
You can pass options as the second parameter of transform method. See examples here
TLDR: I want to read in a file's contents and then export a function which relies on those contents ... without making that exported function use promises or some other form of asynchronicity.
I'm trying to write an XML-validating module, and in order for it to do its thing I need to read in an XSD file. However, this only needs to happen once at "load time", so ideally I'd rather not have other modules that use my function have to wait for a promise to resolve to get their results. If I were using Webpack this would be easy, as I could use it's text file loader to bring in the XSD as if it were any other module ... but unfortunately I'm not.
In other words, currently I have to do (borderline pseudo-code):
module.exports.validate = () =>
new Promise((resolve) =>
fs.readFile(path, (file) => {
// use file to validate, then:
resolve(validationResult);
});
});
};
and instead I'd like to do:
fs.readFile(path, (file) => {
module.exports.validate = myValidationFunction;
});
But the above doesn't work because you can't export from callbacks, so my question is, is there any other way to accomplish this?
The https://github.com/jonschlinkert/to-exports library seems to offer exactly this, so it seems like it's possible ... but it doesn't work for me :(
P.S. At worst I could literally wrap the contents of the file inside the template string characters, rename the file to be .js, and export it that way:
module.exports = `*XSD contents go here*`;
However, that seems very kludgy, so I'm hoping there is a better way.
If you want to read a file synchronously, then use fs.readFileSync. It returns the contents of the file or throws an error.
Hey actually i am doing some project in Nodejs. I need a configuration file in order to store the data to file system but i do not know how to write a configuration file to store data to file. please help me with this. thanks in advance
Sounds to me that you are looking for the following NPM module/library - dotenv. You simply require('dotenv').config(); which is probably best placed at the top (after use strict;) and create a text file which would read as an example:
url_prefix='mongodb://'
url_ip='#localhost'
port=':27017/'
dbase='NameofDB'
Of course you can add anything you like to this file. Just remember it is a text file and should not contain spaces etc.
Though the default for the .env file is in the root of your project you can actually place it wherever you like, and simply put:
require('dotenv').config({path: '/custom/path/to/your/env/vars'});
(Above was taken from the dotenv documentation and it works as I use it in projects.)
To acquire any Global variable you would simply type:
process.env.url_prefix
Obviously from there you can build the needed entry code to your DB from process.env statements such as:
process.env.url_prefix+process.env.url_ip etc. OR
${process.env.url_prefix}${process.env.url_ip}
Using dotenv allows you to keep sane control over those process.env globals.
Be aware there is a gotcha! Be careful not to overwrite any of those globals in your code. As they will remain overwritten as long as your Node process is running.
If you mean you need some constants and business logic/data file to read from, you can simply include the file in your script using the require module.
Ex: Your file name is test.json, then:
var test = require('test.json');
Further, you can use a CONSTANT in the file as 'test.CONSTANT'
Note: Please make sure you use module.exports wherever needed. Details are here
Usually people use JSON to store configurations and stuff, since it is very javascripty.. You can simply make a JSON config file. In case you need to store some special data like SECRET URL, just use environment variables. FYI I found your question unclear. Does this answer your question.
const fs = require("fs");
// Example Config
let config = {
DB: "mongodb://blahblah:idhdiw#jsjsdi",
secret: "thisandthat",
someScript: "blah.js"
};
// Write to file.
fs.writeFile('config.cfg', JSON.stringify(config), err => {
if (err) throw err;
console.log("[+] Config file saved!");
// Retrieve
let confData = JSON.parse(fs.readFileSync('config.cfg'));
console.log(confData.secret);
});
// To save variables in environment variables
// Generally You will not set environment variables like this
// You will have access to setting environment variables incase
// you are using heroku or AWS from dash board. Incase of a machine
// you can use ** export SOME_ENV_VAR="value" ** in your bash profile
process.env.IP = "10.10.10.10";
// Too risky to put else where.
process.env.API_KEY = "2ke9u82hde82h8";
// Get Data
console.log(process.env.IP);
console.log(process.env.API_KEY);
There seems to be no output option in webpack to write the output as a string, either to a nodejs Buffer or to stdout. Googling has yielded nothing promising. Is this possible, via either configuration or 3rd-party-module?
You can write to an in-memory filesystem and read from it after compilation:
const compiler = webpack({ / options / });
const outputFileSystem = new webpack.MemoryOutputFileSystem()
compiler.outputFileSystem = outputFileSystem;
compiler.run((err, stats) => {
// Read the output later:
const content = outputFileSystem.readFileSync('...');
});
This involves calling webpack via its Node API, but the same may also be accomplished entirely in webpack.config.json by creating a custom webpack plugin that changes the compiler’s outputFileSystem on apply.
After researching, the only way I see to accomplish this would be to monkey-patch webpack's NodeOutputFileSystem.writeFile to capture the string contents.
I ended up using raw babeljs instead of webpack to get the string.