fs#openSync TypeScript Examples

The following examples show how to use fs#openSync. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: dbtProjectLog.ts    From vscode-dbt-power-user with MIT License 6 votes vote down vote up
private readLogFileFromLastPosition(event: ProjectConfigChangedEvent): void {
    const { projectRoot } = event;
    if (this.outputChannel) {
      let fileHandle;
      try {
        fileHandle = openSync(
          path.join(
            projectRoot.fsPath,
            DBTProjectLog.LOG_PATH,
            DBTProjectLog.LOG_FILE
          ),
          "r"
        );
        const chunkSize = 1024 * 1024;
        const buffer = Buffer.alloc(chunkSize);
        while (true) {
          const bytesRead = readSync(
            fileHandle,
            buffer,
            0,
            buffer.length,
            this.logPosition
          );
          if (!bytesRead) {
            break;
          }
          this.logPosition += bytesRead;
          this.outputChannel.appendLine(buffer.toString("utf8", 0, bytesRead));
        }
      } catch (error) {
        console.log("Could not read log file", error);
      } finally {
        if (fileHandle) {
          closeSync(fileHandle);
        }
      }
    }
  }
Example #2
Source File: update-file-modification-date.ts    From google-photos-exif with MIT License 6 votes vote down vote up
export async function updateFileModificationDate(filePath: string, timeTaken: string): Promise<void> {
  const time = new Date(timeTaken);

  try {
    utimesSync(filePath, time, time);
  } catch (error) {
    closeSync(openSync(filePath, 'w'));
  }
}
Example #3
Source File: load-flash.ts    From rp2040js with MIT License 6 votes vote down vote up
export function loadMicropythonFlashImage(filename: string, rp2040: RP2040) {
  const file = openSync(filename, 'r');
  const buffer = new Uint8Array(MICROPYTHON_FS_BLOCKSIZE);
  let flashAddress = MICROPYTHON_FS_FLASH_START;
  while (readSync(file, buffer) === buffer.length) {
    rp2040.flash.set(buffer, flashAddress);
    flashAddress += buffer.length;
  }
  closeSync(file);
}
Example #4
Source File: load-flash.ts    From rp2040js with MIT License 6 votes vote down vote up
export function loadUF2(filename: string, rp2040: RP2040) {
  const file = openSync(filename, 'r');
  const buffer = new Uint8Array(512);
  while (readSync(file, buffer) === buffer.length) {
    const block = decodeBlock(buffer);
    const { flashAddress, payload } = block;
    rp2040.flash.set(payload, flashAddress - FLASH_START_ADDRESS);
  }
  closeSync(file);
}
Example #5
Source File: spFormat.ts    From sourcepawn-vscode with MIT License 5 votes vote down vote up
public provideDocumentFormattingEdits(
    document: TextDocument,
    options: FormattingOptions,
    token: CancellationToken
  ): ProviderResult<TextEdit[]> {
    // Get the user's settings.
    let insertSpaces: boolean =
      Workspace.getConfiguration("editor").get("insertSpaces") || false;
    let UseTab: string = insertSpaces ? "Never" : "Always";
    let tabSize: number =
      Workspace.getConfiguration("editor").get("tabSize") || 2;

    let workspaceFolder = Workspace.getWorkspaceFolder(document.uri);
    let defaultStyles: string[] =
      Workspace.getConfiguration("sourcepawn", workspaceFolder).get(
        "formatterSettings"
      ) || [];

    let default_style: string = "{" + defaultStyles.join(", ") + "}";

    // Apply user settings
    default_style = default_style
      .replace(/\${TabSize}/g, tabSize.toString())
      .replace(/\${UseTab}/g, UseTab);
    const start = new Position(0, 0);
    const end = new Position(
      document.lineCount - 1,
      document.lineAt(document.lineCount - 1).text.length
    );
    const range = new Range(start, end);
    const tempFile = join(__dirname, "temp_format.sp");
    let file = openSync(tempFile, "w", 0o765);
    writeSync(file, document.getText());
    closeSync(file);
    let text = this.clangFormat(tempFile, "utf-8", default_style);

    // If process failed,
    if (text === undefined) {
      window.showErrorMessage(
        "The formatter failed to run, check the console for more details."
      );
      return undefined;
    }
    text = fixFormatting(text);
    return [new TextEdit(range, text)];
  }
Example #6
Source File: spLinter.ts    From sourcepawn-vscode with MIT License 4 votes vote down vote up
/**
 * Lint a TextDocument object and add its diagnostics to the
 * @param  {TextDocument} document    The document to lint.
 * @returns void
 */
export function refreshDiagnostics(document: TextDocument): void {
  // Check if the user specified not to enable the linter for this file.
  const range = new Range(0, 0, 1, 0);
  const text = document.getText(range);

  // Check if the setting to activate the linter is set to true.
  const workspaceFolder = Workspace.getWorkspaceFolder(document.uri);
  const enableLinter: boolean = Workspace.getConfiguration(
    "sourcepawn",
    workspaceFolder
  ).get<boolean>("enableLinter");

  // Stop early if linter is disabled.
  if (
    text === "" ||
    /\/\/linter=false/.test(text) ||
    !enableLinter ||
    extname(document.fileName) !== ".sp"
  ) {
    compilerDiagnostics.set(document.uri, []);
    return;
  }

  const tmpPath = join(
    extensions.getExtension("Sarrus.sourcepawn-vscode").extensionPath,
    "tmpCompiled.smx"
  );
  const tmpFile = join(__dirname, "temp.sp");
  const spcomp =
    Workspace.getConfiguration("sourcepawn", workspaceFolder).get<string>(
      "SpcompPath"
    ) || "";

  if (!spcomp) {
    return;
  }

  // Get the previous instance of spcomp if it exists
  let throttle = throttles[document.uri.path];
  if (throttle === undefined) {
    throttle = new TimeoutFunction();
    throttles[document.uri.path] = throttle;
  }

  // Cancel the previous instance and start a new one.
  throttle.cancel();
  throttle.start(() => {
    const mainPath = findMainPath(document.uri);

    // Separate the cases if we are using mainPath or not.
    let scriptingFolder: string;
    let filePath: string;
    if (mainPath !== undefined && mainPath !== "") {
      scriptingFolder = dirname(mainPath);
      filePath = mainPath;
    } else {
      scriptingFolder = dirname(document.uri.fsPath);
      let file = openSync(tmpFile, "w", 0o765);
      writeSync(file, document.getText());
      closeSync(file);
      filePath = tmpFile;
    }

    // Generate compiler arguments.
    const compilerArgs = [
      "-i" +
        Workspace.getConfiguration("sourcepawn", workspaceFolder).get(
          "SourcemodHome"
        ) || "",
      "-i" + scriptingFolder,
      "-i" + join(scriptingFolder, "include"),
      "-v0",
      filePath,
      "-o" + tmpPath,
    ];

    // Add a space at the beginning of every element, for security.
    Workspace.getConfiguration("sourcepawn", workspaceFolder)
      .get<string[]>("linterCompilerOptions")
      .forEach((e) => compilerArgs.push(" " + e));

    // Add the optional includes folders.
    getAllPossibleIncludeFolderPaths(document.uri, true).forEach((e) =>
      compilerArgs.push(`-i${e}`)
    );

    // Run the blank compile.
    execFile(spcomp, compilerArgs, (error, stdout) => {
      // If it compiled successfully, delete the temporary files.
      if (!error) {
        unlink(tmpPath, (err) => {
          if (err) {
            console.error(err);
          }
        });
      }
      parseSPCompErrors(
        stdout,
        compilerDiagnostics,
        mainPath === undefined ? document.uri.fsPath : undefined
      );
    });
  }, 300);
}