[英]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
}
從我的節點腳本中,我需要以某種方式讀取此文件並執行以下操作:
input
object 中具有以icons/
開頭的鍵的所有條目input
object 的新條目。 在 Node 中是否有推薦的方法來執行此操作,我一直在查看幾個庫,例如replace-in-file
但似乎沒有一個適合這種特殊情況。
剛剛面臨同樣的問題,這是我解決它的方法:
.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 應用程序,它將為您提供當前的工作目錄路徑。
.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') );
// ...
myObject.options.foo = 'An awesome option value';
您可以簡單地使用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.