简体   繁体   中英

Issues writing currency symbols to file in nodejs

I am trying to write to a file:

private async writeToFile(data: any) {
    try {
        fs.writeFile(filePath as string, JSON.stringify(data), 'utf8', (error: any) => {
            if (error) {
                logger.error(`[JSON] Error while saving file : ${error}`);
            }
            logger.info('The file has been saved!');
        });
    } catch (error) {
        logger.error(`[JSON] Error while saving file : ${error}`);
    }
}

where data has:

var data = [{label:'Egyptian Pound £', value: 'E£'}, {"label":"Albanian Lek-AL","value":"AL"}];

When I write to file, the characters are saved as {label: Egyptian Pound E , value: E }

The data array is created from a multi line string returned from server:

Egyptian Pound|E£   
Albanian Lek|AL    

Code to create the data array:

const currencyArr = response
    .split('\n')
    .map(val => val.trim())
    .reduce((arr, currencyString) => {
        arr.push({
            label: currencyString.split('|')[0] + '-' + currencyString.split('|')[1],
            value: currencyString.split('|')[1]
        });
        return arr;
    }, []);
this.writeToFile(currencyArr);

I am not sure why this is happening. As per docs, node supports UTF-8 encoding by default

The only reason I can find this kind of thing happen is if your JS file is the one not encoded in UTF8.

Make sure the JS file is saved in the UTF8 encoding, so the string in your script can be saved to the corresponding encoding.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM