How to generate a Google Document inside a specific Drive directory

I’m trying to figure out how to make a new Google document inside a particular Google Drive directory using Google Apps Script.

I already know how to make regular files in folders with this approach:

var myFolder = DriveApp.createFolder("My New Folder")
myFolder.createFile("document.txt", "Hello world")

However, this creates a basic text file, not an actual Google document. What I need is to create a proper Google Docs document that opens in the Google Docs editor when clicked. I’ve been searching for the right method but can’t seem to find the correct way to do this. Can someone show me how to accomplish this task?

Here’s a cleaner approach - use the Drive API directly with the right MIME type. You can create the Google Doc straight in your target folder without moving it around:

var folderId = "your_folder_id_here";
var resource = {
  name: "My New Document",
  parents: [folderId],
  mimeType: "application/vnd.google-apps.document"
};
var doc = Drive.Files.create(resource);

You’ll need to enable the Drive API service in your Apps Script project first. I like this method better since there’s no messy creation in root then moving stuff around. Creates a proper Google Doc that opens in the editor exactly like you want.

both methods r good, but i prefer DocumentApp. it’s simpler, no need for extra APIs. just remember to get the folder ref first - i messed that up once and wasted hours trying to figure out why it failed lol

Use DocumentApp, not DriveApp, to create Google Docs files. Create the document first, then move it to your folder:

var doc = DocumentApp.create("My Document Name");
var docFile = DriveApp.getFileById(doc.getId());
var targetFolder = DriveApp.getFolderById("your_folder_id_here");
targetFolder.addFile(docFile);
DriveApp.getRootFolder().removeFile(docFile);

That last line removes it from the root directory since Google Docs get created there by default. I’ve used this in several automation projects - works reliably. Just make sure you’ve got the right folder ID from the folder’s URL in Drive.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.