javascript - 使用 Node 更新(写入)单独 JS 文件中的对象

标签 javascript node.js

我对 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 脚本中,我需要以某种方式读取此文件并执行以下操作:

  1. 删除 input 对象中所有以键开头的条目 带有图标/
  2. 将新条目附加到input 对象。
  3. 将这些更改写回原始配置文件。

在 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/

相关文章:

node.js - 将用户保存到 MongoDB 的 Passport Facebook 策略

node.js - "npm i"显示损坏的输出 ( "Enter passphrase for key...") 和微调器,输入密码不执行任何操作

php - 年 View 日历

php - 去除黑边 4 :3 on youtube thumbnails

MySQL 与 Node.js

javascript - amCharts 不平衡

javascript - Socket.io 需要很长时间才能触发断开连接事件

javascript - 将新单元格添加到现有行

javascript - 从由 Id Vuejs 过滤的数组中删除对象

javascript - 将数据从 mongodb 传递到我的前端应用程序