Q:

Javascript rename function (not variable name)

I am trying to change the name of the function that is given by .toString(), or create a new function with a new name but the same body.
function func() {}
func.toString() // returns 'function func() {}'
changename(func, "newname") // this is the functionality that I am trying to achieve
func.toString() // should now return 'function newname() {}'

I have tried using Object.defineProperty() which sucessfully updates the value returned by func.name but not func.toString().
Object.defineProperty(func, "name", {
  value: "newname",
  writable: true,
});
func.name // returns 'newname'
func.toString() // still returns 'function func() {}'

Edit: Reason for wanting to do this
I need take take an arbitrary function with an unknown name and write it to a file with a known name, for example (using nodejs):
const fs = require("fs");
changename(func, "newname");
fs.writeFileSync("tmp.js", func.toString());

tmp.js then contains:
function newname() {}

A:

If all you need to do is write the code of the function to a file, just regex replace the name with whatever you want:
let func = // whatever;

let funcCode = func.toString();
funcCode = funcCode.replace(/^function [^(]*(.*)$/, "function newName$1");

Now funcCode has the text you can dump out to a file.
Changing the reported "name" property of an actual function object is another story entirely, and is either impossible or impractical at best. If you're just working with the text of the function, it's easy.

