我对 Node 还很陌生,正在绞尽脑汁地思考如何实现以下目标:
我有一个如下所示的配置文件:
// 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
}
从我的 Node 脚本中,我需要以某种方式读取此文件并执行以下操作:
- 删除
input
对象中所有以键开头的条目 带有图标/
- 将新条目附加到
input
对象。 - 将这些更改写回原始配置文件。
在 Node 中是否有推荐的方法来执行此操作,我一直在查看几个库,例如 replace-in-file
但似乎没有一个适合这种特殊情况。
最佳答案
刚刚遇到同样的问题,这是我的解决方法:
1。获取您的文件内容
- 如果它不是
.js
文件,则使用fs.readFileSync
(或fs.readFile
)就像这样:
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
文件(例如,像webpack.config.js
这样的 JavaScript 配置文件),则只需使用require
native 函数,就像处理常规内部文件或 NPM 模块一样,您将获得所有module.export
内容:
const path = require('path');
const myObject = require( path.join( process.cwd(), 'myFile.js') );
2。根据需要修改您的对象
// ...
myObject.options.foo = 'An awesome option value';
3。然后重写回文件
您可以简单地使用 fs.writeFileSync
实现这一目标:
// ...
fs.writeFileSync( path.join(process.cwd(), 'my-file.txt', myObject );
如果你想编写一个普通的 JavaScript 对象,那么你可以使用 util.inspect()
native 方法,您也可以使用 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));
关于javascript - 使用 Node 更新(写入)单独 JS 文件中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61087849/