如何在 JavaScript 字符串中创建换行符以提供给 NodeJS 以写入文本文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14173150/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 15:55:03  来源:igfitidea点击:

How do I create a line break in a JavaScript string to feed to NodeJS to write to a text file?

javascriptnode.jsjquery

提问by guypursey

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):

我创建了一个简单的 HTML 页面,它从用户那里获取一些输入以存储在服务器上以供稍后检索——这就是当用户单击提交按钮时文本的处理方式(我在键下放置了编号的评论行,但提供上下文的周围代码):

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);
    }
});

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

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

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 + ' })');
        }
    });
}

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:

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

{ "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.

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

I have tried using \nand \tlike so:

我试过使用\n\t喜欢这样:

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

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

我也试过了\r。但这条线仍然没有中断。

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

一些答案表明我只能在编码字符串级别在写入文件后执行此操作。也许我错过了一些简单的东西。有没有办法通过操纵我的jsonText变量来做到这一点?

UPDATE:

更新:

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"
}

回答by Christophe Keller

Use

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

回答by guypursey

It turns out that when writing a string to a (text) file with Node.js [EDIT: in Windows], use \r\nfor a new line.

事实证明,当使用 Node.js [编辑:在 Windows 中]将字符串写入(文本)文件时,使用\r\n换行。

As with encoded line breaks, both a return carriage and a new line is necessary. So the line of code needed to be this rather than having just \ror just \n:

编码换行符一样,回车和换行都是必要的。所以代码行需要是这样的,而不是\r只有\n

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

The resulting file's content now displays as desired:

生成的文件内容现在按需要显示:

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