Home > Net >  Unexpected keyword or identifier.ts(1434)
Unexpected keyword or identifier.ts(1434)

Time:02-01

I have the following code that tries to read a file from the local machine and upload it to the AWS s3 cloud service:

import AWS from 'aws-sdk';
import fs, { ReadStream } from "fs";
import path from "path";

class Uploads {

  static const bucketName = "myappllbuck";
  static const s3 = new AWS.S3({ apiVersion: '2006-03-01' });
  static const filePath = "/home/s/img2.png";

  static const uploadParams: {
    Bucket: string;
    Key: string;
    Body: string | ReadStream;
    ContentType: any; ACL: string
  } = {
      Bucket: this.bucketName,
      Key: '',
      Body: '',
      ContentType: null,
      ACL: 'public-read',
    };

  static const fileStream  = fs.createReadStream(this.filePath);

  
  fileStream.on('error', function(err) {
    console.log('File Error', err);
  });
   this.uploadParams.Body = this.fileStream;
   this.uploadParams.Key = path.basename(filePath);
   this.uploadParams.ContentType = 'image/png';
   this.uploadParams.ACL = 'public-read';
}

But I get the following error @fileStream.on() line:

Unexpected keyword or identifier.ts(1434)
Member 'fileStream' implicitly has an 'any' type.ts(7008)

And the following error @this.UploadParams. lines of the code:

Unexpected token. A constructor, method, accessor, or property was expected.ts(1068)
Object is possibly 'undefined'.ts(2532)

CodePudding user response:

The code starting from fileStream.on('error', function(err) { is still inside the class. Make sure to close the class declaration before running this code.

CodePudding user response:

The problem is that the fileStream and uploadParams properties are static properties of the Uploads class and cannot be accessed using the this keyword.

To resolve the issue, you need to access the properties using the class name instead:

  static fileStream = fs.createReadStream(this.filePath);

  
  static fileStream.on('error', function(err) {
    console.log('File Error', err);
  });
  static uploadParams: {
    Bucket: string;
    Key: string;
    Body: string | ReadStream;
    ContentType: any; ACL: string
  } = {
      Bucket: this.bucketName,
      Key: '',
      Body: '',
      ContentType: null,
      ACL: 'public-read',
    };
   Uploads.uploadParams.Body = Uploads.fileStream;
   Uploads.uploadParams.Key = path.basename(Uploads.filePath);
   Uploads.uploadParams.ContentType = 'image/png';
   Uploads.uploadParams.ACL = 'public-read';

Note: It is also possible to move the properties and the on method outside the class as separate constants and functions, and then use them in the class.

  • Related