How do I programmatically store a file reference in a node?
Assume, we have content type : Image

It have following fields in the content type.


title
field_imagedata for Image field


Now, we want to create custom node.

Step : 1  We need to get static image path which we would like to attach in the node. We have in "sites\default\files\2017-01\source.png"

So, In drupal, we could access this image uri by "public://2017-01/source.png".

Step : 2 We need to create file reference in our Drupal database. Se we need to use "File::Create" method.

Step : 3 After that, we could generate node using "entity_create".

Please look at the whole code.

    $uri  = file_unmanaged_copy("public://2017-01/source.png", "public://2017-01/destinatio.jpg", FILE_EXISTS_REPLACE);
    $file = File::Create([
      'uri' =&gt; $uri,
    ]);
    $file-&gt;save();

    $new_page_values = array();
    $new_page_values['type'] = 'image';
    $new_page_values['title'] = "PARAG";
    $new_page_values['field_imageda'] = array('target_id' =&gt; $file-&gt;id());
    $new_page = entity_create('node', $new_page_values);
    $new_page-&gt;save();


Also, you could update the node, by using the following code.

    // Load existing node and attach file.
    $node = Node::load(1); 
    $node-&gt;field_imageda-&gt;setValue([
      'target_id' =&gt; $file-&gt;id(),
    ]);
    $node-&gt;save();


Using this code, you could create new node with the static file.