如何在JavaScript字符串中创建换行符以馈送给NodeJS以写入文本文件? [英] How do I create a line break in a JavaScript string to feed to NodeJS to write to a text file?

查看:576
本文介绍了如何在JavaScript字符串中创建换行符以馈送给NodeJS以写入文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个简单的HTML页面,该页面吸收了用户的一些输入以存储在服务器上以供以后检索-这是当用户单击提交"按钮时如何处理文本的方式(我已经给编号的注释添加了编号在关键行下,但提供上下文的周围代码):

I've created a simple HTML page that takes some input from the user to store on a server to be retrieved later -- this is how the text is treated when the user clicks a submit button (I've placed numbered comments under the key lines but provide the surrounding code for context):

var origText = $('#input-field').val(),
        // 1. GETS WHATEVER USER TYPED INTO INPUT FIELD
    jsonText = '{ "text": "' + origText + '" }',
        // 2. WRAPS IT AN OBJECT STRING
    ajaxText = encodeURIComponent(jsonText);
        // 3. ENCODES THE STRING FOR USE WITH AJAX

$.ajax({
    url: 'http://localhost:8124/',
    data: 'save=' + ajaxText + '&fn=save',
        // 4. THE ENCODED STRING IS ADDED TO THE QUERY SECTION OF THE AJAX REQUEST
    dataType: "jsonp",
    cache: false,
    timeout: 5000,
    success: function(data) {
        $("#input-ready").html(data.save.text);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        alert('error ' + textStatus + " " + errorThrown);
    }
});

请求被发送到我在本地运行的NodeJS服务器,该服务器(在http.createServer回调中)执行以下操作:

The request is sent to a NodeJS server I am running locally, which (within the http.createServer callback) does the following:

var queryObj = url.parse(req.url, true).query;
    // 1. GET THE QUERY PART OF THE REQUEST/URL AS AN OBJECT
res.writeHead(200, {'Content-Type': 'application/javascript'});
    // 2. PREPARE SERVER'S RESPONSE AS JAVASCRIPT
queryObj.fn = queryObj.fn || '';
queryObj.save = queryObj.save || '';
queryObj.callback = queryObj.callback || '';
    // 3. ENSURE THE PROPERTIES NEEDED ARE DEFINED, EVEN IF FALSE-Y
if (queryObj.fn === 'save') {
    // 4. IF THE REQUEST IS TO SAVE THEN WRITE THE USER INPUT AS OBJECT TO A TEXT FILE
    fs.writeFile('jsonp-storage-2.txt', queryObj.save, function (err) {
        if (err) {
            throw err;
        } else {
            console.log('Saved message successfully.', 'Ready to be read now.');
            res.end(queryObj.callback +
                '({ fn: "' + queryObj.fn + '", save: ' + queryObj.save + ' })');
        }
    });
}

假设用户键入并提交这是一行文本",则服务器上的输出是一个名为jsonp-storage-2.txt的文本文件,其中包含以下内容:

Assuming the user types and submits "this is a line of text", the output on the server is a text file called jsonp-storage-2.txt containing this:

{ "text": "this is a line of text" }

毕竟,我的问题很简单.如何在文本文件中美化输出?

After all that, my question is quite simple. How do I prettify the output in the text file?

代码需要工作,但是我正在考虑使用它来尝试存储较大的对象以供以后阅读.但是,在服务器端,例如,当我使用记事本打开文件时,我希望这些文件(现在)易于阅读.

The code needs work but I'm thinking of using this to try storing larger objects for reading later. However, at the server end, I would like the files (for now) to be easy for me to read when opening them with Notepad, for example.

我曾尝试像这样使用\n\t:

I have tried using \n and \t like so:

jsonText = '{\n\t"text": "' + origText + '"\n}',

我也尝试过\r.但是这些线保持不间断.

I've also tried \r. But the lines remain unbroken.

一些答案​​表明,我只能在编码字符串级别执行/a>或在文件写入后.也许我错过了一些简单的事情.有没有办法通过操纵我的jsonText变量来做到这一点?

Some answers suggest that I can only do this at the level of the encoded string or after the file has been written. Perhaps I missed something simple. Is there a way to do it by manipulating my jsonText variable?

更新:

只是更清楚地了解所需的输出-当前生成的文本文件的内容如下所示:

Just to be clearer about the output desired -- currently the content of the text file produced looks like this:

{ "text": "this is a line of text" }

但是我想知道它是否可以这样生产:

But I'd like to know if it can be produced like this:

{
    "text": "this is a line of text"
}

推荐答案

使用

var os = require('os');
var jsonText = '{' + os.EOL + '\t"text": "' + origText + '"' + os.EOL + '}';

这篇关于如何在JavaScript字符串中创建换行符以馈送给NodeJS以写入文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆