Home > Back-end >  Wrap imported file with code before passing to bash/shell command
Wrap imported file with code before passing to bash/shell command

Time:11-16

I have an npm script though I think this would apply to any bash command:

node file.js

The content of file.js for the purpose of the question might be:

console.log('hello')

I would like to wrap the content of file.js in some code so that the final "content" is:

console.log('start')
console.log('hello')
console.log('end')

Right now I have the start/end stuff in a separate file which is the one I call and it in turns, imports the file.js file

// wrapper.js
const foo = import('./file.js') 
console.log('start')
foo() // or whatever...
console.log('end')

Then I call it:

node wrapper.js

This approach works but I am trying to eliminate the wrapper file and pass the content directly - Essentially concatenate 2 strings with content of a file and then have the node utility accept that like a file. (note that this is not specific to node cli)

CodePudding user response:

edit: Charles Duffy's comment recommends a simpler solution if you just want to wrap a file and don't need anything more complex than that.

{ 
 echo "console.log('start')" 
 cat ./file.js
 echo "console.log('end')"
} > ./wrapped.js

You can use cat for this.

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')

This utilizes two process substitutions (the <( command ) syntax) to create temporary files containing the content you want to wrap around your script, then concatenates the three files together into a single file.

If you don't want to write the concatenated data out to a file, you could wrap the whole thing in another process substitution and pass it directly to your command in whatever manner it takes files.

node <(
cat <( printf '%s\n' "console.log('start')" ) \
     ./file.js \
    <( printf '%s\n' "console.log('end')" )
)
  • Related