3

I am trying to write the content of a string in a file in node.js

I have some raml files and I am able to join them. If I print the variable in console, I see it well parsed but as soon as I save in on a file, the file just contains one single line:

var raml = require('raml-parser');
var fs = require('fs');
var path = require('path');
var os = require('os')

path.join(__dirname, './')


raml.loadFile('schema.raml').then( function(data) {
 console.log(data);
  var filePath = "schema.raml"; 
  fs.unlinkSync(filePath);
  fs.writeFile("./new.raml", JSON.stringify(data).replace('/\n', os.EOL),     function(err) {
    if(err) {
        return console.log(err);
    }

    console.log("The file was saved!");
}); 


}, function(error) {
  console.log('Error parsing: ' + error);
    });

I added a replace EOL to change all "\n" in file. If I delete that, file will contain "\n" in each end of line.

On console, this is the output:

{ title: 'RAML Flattener',
  baseUri: 'http://github.com/joeledwards/node-flat-raml',
  version: '1',
  mediaType: 'application/json',
  protocols: [ 'HTTP' ],
  resources: 
   [ { relativeUri: '/base',
       methods: [Object],
       resources: [Object],
       relativeUriPathSegments: [Object] } ] }
Biribu
  • 3,615
  • 13
  • 43
  • 79

1 Answers1

4

data is a Javascript object; how that is being displayed when you console.log() it doesn't have much to do with how it will end up in the file you are writing.

The problem is that you are using JSON.stringify(), which, by default, will not pretty-print the output string.

Instead, try this:

JSON.stringify(data, null, 2)

This will make your output look like this:

{
  "title": "RAML Flattener",
  "baseUri": "http://github.com/joeledwards/node-flat-raml",
  "version": "1",
  "mediaType": "application/json",
  "protocols": [
    "HTTP"
  ],
  "resources": [
    {
      "relativeUri": "/base",
      "methods": { ... },
      "resources": { ... },
      "relativeUriPathSegments": { ... }
    }
  ]
}

You may or may not need to call .replace() on its output. If you do, use this (the one you're using isn't valid):

.replace(/\n/, os.EOL)
robertklep
  • 198,204
  • 35
  • 394
  • 381