2

I generate some jS code on the front end and i want to write it to a js file by making an api call to a node server and i'm having some trouble with 1) ensuring the code isnt written to file as a literal string and 2) ensuring that multiple lines are preserved.

Here's my code for how ive attempted this:

//client
var bar = "mongolia"; //this value changes hence pulling it into variable
var jsCode = "function(){ \n
baz = foo(" + bar + "); \n
   return baz*2;"
var data = {
    code: jsCode
 }
 $http.post('api/code', data).success(function(savedCode){
   console.log("successful and the saved code is", savedCode);
 }); 
//server

'use strict';

var jf = require('jsonfile'),
    util = require('util');

var codeFile = './code/js/autoGen.js';

exports.addCode = function(req, res) {
  var newCode = req.body.code;
    //write to file
  return jf.writeFile(codeFile, newCode, function(err) {
      if(!err) {
        return res.json({newCode: newCode});          
      }
      else {
        return res.send(err);
      }
    });
};

When i run this, I get a syntax error in my jsCode definition.

3
  • A syntax error where? Also, why are you using jsonfile? Can't you just use var fs = require('fs'); fs.writeFile(//...? Commented Dec 15, 2013 at 21:38
  • Also, you should remove all those returns in your exports.addCode Commented Dec 15, 2013 at 21:43
  • syntax error in my jsCode definition--> var jsCode = ..., also no real reason for using jsonfile i was using it in a difft project and converted it...any idea why the core function on the client isn't working though? Commented Dec 15, 2013 at 21:50

2 Answers 2

2

JavaScript syntax for multiline strings is as follows:

var jsCode = "function(){ \
baz = foo(" + bar + "); \
   return baz*2;"
Sign up to request clarification or add additional context in comments.

Comments

0

I got around both issues by

1) Using coffeescript for multiline strings and the #{} interpolation pattern for including the variable portions

2) Using fs for writing to file (Thanks for the tip @verybadalloc)

1 Comment

You don't need coffeescript. Check out @punund's answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.