Is it possible to write a text file in UTF-16 using Javascript?

I need to create a UTF-16 text file from a string. For instance:

var s = "aosjdfkzlzkdoaslckjznx";
var file = "data:text/plain;base64," + btoa(s);

The above code generates a UTF-8 encoding text file. How can I modify it to produce a UTF-16 text file using the string s?

Answer №1

For more information, check out: Dealing with encoding problems when exporting Javascript to csv

Here is the solution that should work:

document.getElementById('download').addEventListener('click', function(){

downloadUtf16('Hello, World', 'myFile.csv')
});

function downloadUtf16(str, filename) {

// reference: https://stackoverflow.com/q/6226189
var charCode, byteArray = [];

// Byte Order Mark for Big Endian
  byteArray.push(254, 255);

// Byte Order Mark for Little Endian
  // byteArray.push(255, 254);

  for (var i = 0; i < str.length; ++i) {
  
    charCode = str.charCodeAt(i);
    
    // Big Endian Bytes
    byteArray.push((charCode & 0xFF00) >>> 8);
    byteArray.push(charCode & 0xFF);
    
    // Little Endian Bytes
    // byteArray.push(charCode & 0xff);
    // byteArray.push(charCode / 256 >>> 0);
  }
  
  var blob = new Blob([new Uint8Array(byteArray)], {type:'text/plain;charset=UTF-16BE;'});
  var blobUrl = URL.createObjectURL(blob);
  
// reference: https://stackoverflow.com/a/18197511
  var link = document.createElement('a');
  link.href = blobUrl;
  link.download = filename;

  if (document.createEvent) {
    var event = document.createEvent('MouseEvents');
    event.initEvent('click', true, true);
    link.dispatchEvent(event);
  } else {
    link.click();
  }
}
<button id="download">Download</button>

Answer №2

To convert a JavaScript string into an ArrayBuffer, you can utilize a legacy polyfill for the native TextEncoder API. The TextEncoder documentation specifies support for UTF16 with different endianness. It is likely that libraries offering UTF-16 support in a Text-Encoder-compatible manner will emerge soon, if they haven't already. For instance, let's imagine there's a library with a constructor named ExtendedTextEncoder.

You can then generate a Blob URL to facilitate file downloads for users, bypassing the cumbersome base-64 conversion process.

Here's an example:

s = "aosjdfkzlzkdoaslckjznx"
var encoder = new ExtendedTextEncoder("utf-16be")
var blob = new Blob(encoder.encode(s), "text/plain")
var url = URL.createObjectURL(blob)

From now on, you can utilize url instead of your data: URL.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Generate a spreadsheet file in xlsx format by using the exceljs library in Node

I am currently working with exceljs 3.8 in an attempt to generate a new XLSX file, but unfortunately the code below seems to be malfunctioning. createNewExcelFile: function (excelFilePath) { //excelFilePath: Path and filename for the Exce ...

Angularjs - Transferring the $scope object to a controller

While taking Angular's complimentary online course, I came across the following code snippet: app.controller('GalleryController', function(){ this.current = 0; this.setCurrent = function(imageNumber){ this.current = imageNumber || 0 ...

What is the best way to pass the index value of a v-for loop as an argument to a computed property function in Vue?

I'm looking to pass the index value from a v-for loop (inside a path tag) as a parameter to a function stateData(index) defined in a computed property in Vue. I attempted to achieve this using v-model="stateData[index]", but an error is being displaye ...

More efficient methods for handling dates in JavaScript

I need help with a form that requires the user to input both a start date and an end date. I then need to calculate the status of these dates for display on the UI: If the dates are in the past, the status should be "DONE" If the dates are in the future, ...

Unable to minimize or hide the ace editor widget with Cypress

Today marks the beginning of my journey into posting on this platform, and I am eager to get it right. In my current project using Cypress for writing integration tests, I encountered a challenge while attempting to click on an Ace editor widget within a ...

Execute JavaScript unit tests directly within the Visual Studio environment

In search of a method to run JavaScript unit tests within the Visual Studio IDE, I currently utilize TestDriven.net for my C# units tests. It's convenient to quickly view the test results in the output pane and I am seeking a similar experience for Ja ...

Executing Bower installation within a corporate proxy network

Encountering Error : ECONNREFUSED Request to https://bower.herokuapp.com/packages/bootstrap-datepicker failed: connect ECONNREFUSED while attempting Bower Install from Package Manager Console. I came across suggestions in a different discussion on how to ...

What is the best way to compare an attribute value with a JSON value in JavaScript?

I have a JSON string that looks like this: { "DocID": "NA2", "DocType": "Phase1.1 - Visa Documents (This section is applicable for HK work location only)", "DocSubType": "New Application", "DocName": "Passport / Travel Document (Soft copy only) ...

What is the optimal approach for managing server-side data stored as a JavaScript variable?

When dealing with global variables like JSON inserted into a web page server side with PHP, the best way to handle it is up for debate. Options might include leaving it for garbage collection, omitting var initialization and deleting the variable, or simpl ...

How can I filter rows in HTML using Vue.js based on string options?

When selecting different options, I want to dynamically add new rows. For instance, if "kfc" is selected, a specific row should be added. If "cemrt" is chosen, another row needs to be included. <div class="card-content" v-for="(bok, index) in rules" :k ...

The function passed to the modal is not functioning correctly when stored within the state

Is it possible to create a unique modal that can be utilized for multiple actions on the same page? To achieve this, I have implemented a state to store the title, description, and submit function for modal click and modal open state. In addition, I want t ...

Exploring the world of WebSockets and Socket.io

Recently many online games, like , have started using WebSockets to create real-time MMORPGs. I'm curious about how to develop a node.js program that can manage connections from browsers using WebSockets. Here is an example of browser code: <!DOC ...

The outcome of the Ajax response is not in accordance with my expectations

Whenever the response from my PHP echo statement in an AJAX request is "loggedIn", I want to invoke the displayUsers function. However, it seems to always skip executing displayUsers() and goes straight to the else statement. Oddly enough, when I alert the ...

Common mistakes encountered when utilizing webpack for react development

I'm currently following the exercises in Pro MERN Stack by Apress and have come across a webpack issue. Everything was running smoothly until I introduced webpack into the mix. Now, when I execute npm run compile, I encounter the following error: > ...

Error message: A circular structure is being converted to JSON in Node.js, resulting in

So here is the error message in full TypeError: Converting circular structure to JSON --> starting at object with constructor 'Socket' | property 'parser' -> object with constructor 'HTTPParser' --- prope ...

Filtering with AngularJS based on integer comparison will assist in stream

Currently, I have implemented a "price" field on my website using the JQuery-UI slider. This field comprises of two integer values: minPrice and maxPrice. Suppose I possess an array of objects structured in this manner: objarr=[ { 'name'=&ap ...

Retrieve items within an array of objects in MongoDB using an array of IDs (using the $in operator in aggregation)

In my MongoDB database, I have a collection of stores [ { "_id" : ObjectId("6043adb043707c034d5363b7"), "shopId" : "shopid1", "appId" : "777", "shopItems" : [ { ...

Looking for a comprehensive calculation that takes into account various input values?

I need to display the List Price at the bottom of the form so users are aware of the cost to list their item. Within a php file, I have defined price brackets. For example, if the listing price is £150.00, it falls between £100 and £199.99 and thus nee ...

Modifying the default error message in Yup: A step-by-step guide

What is the process for modifying the default error message to a custom error message? Specifically, my custom message. const VALIDATION_SCHEME = Yup.object().shape({ numOne: Yup.Number().required('!'), numTwo: Yup.Number() .r ...

Node.js and socket.io come together in this collaborative text editing tool

I'm currently working on a collaborative app utilizing node and sockets that includes a simple text tool feature. My goal is for any user who types and applies text to the canvas to have that text visible to all other connected users. Here's wha ...