Environment variables containing newlines in Node?

后端 未结 8 481
再見小時候
再見小時候 2021-02-02 06:00

I\'m attempting to load an RSA private key into my nodejs application using environment variables, but the newlines seem to be being auto-escaped.

For the following, ass

8条回答
  •  灰色年华
    2021-02-02 06:33

    Node will take the environment vars and escape them to avoid interpolation:

    % export X="hey\nman"
    % echo $X
    hey
    man
    % node
    > process.env['X']
    'hey\\nman'
    >
    

    One option is to set the variable outside of node with actual newlines:

    % export X="hey
    dquote> man"
    % node
    > process.env['X']
    'hey\nman'
    > console.log(process.env['X'])
    hey
    man
    undefined
    >
    

    This also works within script files, just use newlines within quotes. You can also do a replacement:

    % export X="hey\nman\ndude\nwhat"
    % node
    > console.log(process.env['X'].replace(/\\n/g, '\n'))
    hey
    man
    dude
    what
    

提交回复
热议问题