簡體   English   中英

使用 Node 在單獨的 JS 文件中更新(寫入)object

[英]Update (write to) an object in a separate JS file using Node

我對 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
}

從我的節點腳本中,我需要以某種方式讀取此文件並執行以下操作:

  1. 刪除input object 中具有以icons/開頭的鍵的所有條目
  2. Append input object 的新條目。
  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

這里我使用的是process.cwd() ,如果是 CLI 應用程序,它將為您提供當前的工作目錄路徑。

  • 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內容:
const path = require('path');
const myObject = require( path.join( process.cwd(), 'myFile.js') );

2. 根據需要修改您的 object

// ...
myObject.options.foo = 'An awesome option value';

3.然后重寫回文件

您可以簡單地使用fs.writeFileSync來實現:

// ...
fs.writeFileSync( path.join(process.cwd(), 'my-file.txt', myObject );

如果你想寫一個普通的 JavaScript Object,那么你可以使用util.inspect()本機方法,你也可以使用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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM