Last Updated: November 03, 2016
· jabclab

Native object copy in Node.js

In order to shallow clone an Object in Node.js we can use the following method from util:

var extend = require('util')._extend;

var original = { foo: 'bar' };
var extended = extend(original, { another: 'attribute' }); 
// { foo: 'bar', another: 'attribute' }

This _extend function can be found in the Node.js source here.

I discovered this via this StackOverflow answer.

3 Responses
Add your response


Now Node.js source is https://github.com/joyent/node/blob/master/lib/util.js#L640
It changes over time just because node.js source code changes as well :)

over 1 year ago ·

You have to bear in mind your node.js version. If you're running Azure Mobile Services for example, you won't have the _extend util. Here are the docs: http://nodejs.org/docs/v0.8.28/api/util.html

over 1 year ago ·

As mentionned on https://nodejs.org/docs/latest/api/util.html#util_util_extend_target_source

The util._extend() method was never intended to be used outside of internal Node.js modules. The community found and used it anyway.

=> use Object.assign

over 1 year ago ·