Reputation: 2635
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:
input
object that have a key starting
with icons/
input
object.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.
Upvotes: 2
Views: 2914
Reputation: 655
Just faced the same concern, here is how I solved it :
.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.
.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') );
// ...
myObject.options.foo = 'An awesome option value';
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));
Upvotes: 2