How to create Node programmatically in Drupal 8

Creation of the Node programmatically it's pretty usual task. For example for batch operations or something else.

Here is a short piece of code, which demonstrated how to do this:

use Drupal\node\Entity\Node;

$my_article = Node::create(['type' => 'article']);
$my_article->set('title', 'My article');
$my_article->set('field_text', 'My text');
$my_article->set('field_user', UID);
$my_article->set('field_file', FID);
$my_article->enforceIsNew();
$my_article->save();

I hope that it was useful.

Tags: