4

I have a nodejs project. Where i have few dependencies in package.json

in the "scripts" section i have added "preinstall":"node preinstall"

The preinstall script generates the dependencies on the runtime and update package.json, so that can be available for actuall npm install call.

preinstall.js is something like this

const pkg = require('./package.json')
pkg.dependencies['new-package'] = 'latest';
require('fs').writeFileSync('./package.json', JSON.stringify(pkg, null, 2))

I get an additional diff as below in package.json

-}
\ No newline at end of file
+}

How to get rid of this? I don't want this diff after i write the json file.

codeofnode
  • 18,169
  • 29
  • 85
  • 142
  • 1
    You should: **1.** Manually add a newline to the end of your `package.json` before running your node script as It's good practice to include a trailing new line as explained [here](https://stackoverflow.com/questions/5813311/no-newline-at-end-of-file). **2.** Commit that change to git. . **3.** Once you've done that change the `JSON.stringify(pkg, null, 2)` part in your node script to `JSON.stringify(pkg, null, 2).concat('\n')` - note the addition of `.concat('\n')`. **4.** You should then not see _"No newline ..."_ mentioned in future diffs after your `preinstall` script runs. – RobC May 31 '18 at 17:41
  • It's also worth noting that the _"No newline..."_ message doesn't seem related to the resultant output from your node script. It's probable that `git diff` will show you this if you were to manually make a change to _package.json_ anyway (i.e. not via the node script). This is simply because your _package.json_ does not initially include a trailing newline character. – RobC Jun 01 '18 at 07:59
  • even doing this `require('fs').writeFileSync(JSON.stringify(pkg, null, 2)+'\n')` does not help. Don't know why. So i thought to deal with it. – codeofnode Jun 02 '18 at 17:08
  • [`fs.writeFileSync()`](https://nodejs.org/api/fs.html#fs_fs_writefilesync_file_data_options) expects the first argument to be a filename or file descriptor. Your code should be: `require('fs').writeFileSync('./package.json', JSON.stringify(pkg, null, 2)+'\n')`. Also did you do points 1 and 2 mentioned in my initial comment? – RobC Jun 02 '18 at 20:15
  • oh.. actually i missed that in asking questions.. thanks for pointing. Real code is just way too different – codeofnode Jun 03 '18 at 08:26

1 Answers1

4

Already mentioned by @RobC in the comments, just putting it in an actual answer:

The problem is that JSON.stringify correctly adds newline characters on each line, but then fails to insert one on the last line. It results in malformed text files when written to a file (producing No newline at end of file warnings etc).

In any case, the solution is to manually add the missing newline by replacing

JSON.stringify(pkg, null, 2)

with

JSON.stringify(pkg, null, 2).concat('\n')
friederbluemle
  • 33,549
  • 14
  • 108
  • 109