使用nodeJS和cheerio写入HTML文件时得到特殊字符而不是单引号

时间:2018-11-28 08:30:37

标签: node.js html-entities cheerio

我只是在玩弄节点,所以我想在我的html文件中替换以下html

Private Sub Workbook_AfterSave(ByVal Success As Boolean)

If Success = True Then
    'Step 1: Define WS variable
        Dim ws As Worksheet
    'Step 2: Unhide the Starting Sheet
        Sheets("START").Visible = xlSheetVisible
    'Step 3: Start looping through all worksheets
        For Each ws In ThisWorkbook.Worksheets
    'Step 4: Check each worksheet name
        If ws.Name <> "Start" Then
    'Step 5: Hide the sheet
        ws.Visible = xlVeryHidden
        End If
    'Step 6: Loop to next worksheet
        Next ws
    'Step 7: Save the workbook
        ActiveWorkbook.Save
    'Step 8: Start looping through all worksheets
        For Each ws In ThisWorkbook.Worksheets
    'Step 9: Re-Unhide All Worksheets
        ws.Visible = xlSheetVisible
    'Step 10: Loop to next worksheet
        Next ws
    'Step 11: Re-Hide the Start Sheet
        Sheets("START").Visible = xlVeryHidden
    'Step 12: Exit loop
        If ThisWorkbook.Saved = True Then
        Exit Sub
        End If
End If
End Sub

想要将其替换为

<div class="replace" onclick="opennewtab('one')">

所以我有以下节点代码:

<div class="replace" onclick="replacedFunc('12345&')">

但是我得到的是

let fs = require('fs'),
cheerio = require('cheerio');

$ = cheerio.load( fs.readFileSync( `${__dirname}/res/writetojs.html` ) );
$('.replace').attr('onclick' , "replacedFunc('12345')");
console.log($.html());
inner_content =  $.html();
fs.writeFileSync( `${__dirname}/res/newwritetojs.html` , inner_content, 'utf8');

我如何获得<div class="replace" onclick="replacedFunc(&apos;12345&apos;)"> 而不是'

1 个答案:

答案 0 :(得分:3)

Cheerio默认情况下正在解码HTML实体,需要时,您可以通过传递decodeEntities: false选项关闭此功能

这里是一个例子:

$ = cheerio.load( fs.readFileSync( `${__dirname}/res/writetojs.html` ), {decodeEntities: false} );