我有一個 npm 腳本,盡管我認為這適用于任何 bash 命令:
node file.js
出于問題目的的內容file.js可能是:
console.log('hello')
我想將 的內容包裝file.js在一些代碼中,以便最終的“內容”是:
console.log('start')
console.log('hello')
console.log('end')
現在我在一個單獨的檔案中有開始/結束的東西,這是我呼叫的檔案,它依次匯入file.js檔案
// wrapper.js
const foo = import('./file.js')
console.log('start')
foo() // or whatever...
console.log('end')
然后我稱之為:
node wrapper.js
這種方法有效,但我試圖消除包裝檔案并直接傳遞內容——本質上是將 2 個字串與檔案內容連接起來,然后讓node實用程式像接受檔案一樣接受它。(請注意,這不是特定于節點 cli 的)
uj5u.com熱心網友回復:
編輯:Charles Duffy 的評論推薦了一個更簡單的解決方案,如果您只想包裝一個檔案并且不需要比這更復雜的東西。
{
echo "console.log('start')"
cat ./file.js
echo "console.log('end')"
} > ./wrapped.js
你可以用cat這個。
printf '%s\n' "console.log('hello')" > ./file.js
cat <( printf '%s\n' "console.log('start')" ) \
./file.js \
<( printf '%s\n' "console.log('end')" ) \
> ./wrapped.js
cat ./wrapped.js
# outputs:
# console.log('start')
# console.log('hello')
# console.log('end')
這利用兩個行程替換(<( command )語法)來創建臨時檔案,其中包含您要環繞腳本的內容,然后將這三個檔案連接成一個檔案。
如果您不想將連接的資料寫出到一個檔案中,您可以將整個事情包裝在另一個行程替換中,并以任何需要檔案的方式將其直接傳遞給您的命令。
node <(
cat <( printf '%s\n' "console.log('start')" ) \
./file.js \
<( printf '%s\n' "console.log('end')" )
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/535679.html
標籤:狂欢壳
下一篇:避免捕獲相似的檔案夾名稱
