1 /*
2 * Copyright (c) 2024 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #include "create_streamrw.h"
17
18 #include "file_utils.h"
19 #include "filemgmt_libhilog.h"
20
21 namespace OHOS {
22 namespace FileManagement {
23 namespace ModuleFileIO {
24 using namespace std;
25 using namespace OHOS::FileManagement::LibN;
26 const string READ_STREAM_CLASS = "ReadStream";
27 const string WRITE_STREAM_CLASS = "WriteStream";
28
CreateStream(napi_env env,napi_callback_info info,const string & streamName)29 static napi_value CreateStream(napi_env env, napi_callback_info info, const string &streamName)
30 {
31 NFuncArg funcArg(env, info);
32 if (!funcArg.InitArgs(NARG_CNT::ONE, NARG_CNT::TWO)) {
33 HILOGE("Number of arguments unmatched");
34 NError(EINVAL).ThrowErr(env);
35 return nullptr;
36 }
37 size_t argc = funcArg.GetArgc();
38 const char moduleName[] = "@ohos.file.streamrw";
39 napi_value streamrw;
40 napi_load_module(env, moduleName, &streamrw);
41 napi_value constructor = nullptr;
42 napi_get_named_property(env, streamrw, streamName.c_str(), &constructor);
43 napi_value streamObj = nullptr;
44 napi_status status;
45 if (argc == NARG_CNT::ONE) {
46 napi_value argv[NARG_CNT::ONE] = {funcArg[NARG_POS::FIRST]};
47 status = napi_new_instance(env, constructor, argc, argv, &streamObj);
48 } else {
49 napi_value argv[NARG_CNT::TWO] = {funcArg[NARG_POS::FIRST], funcArg[NARG_POS::SECOND]};
50 status = napi_new_instance(env, constructor, argc, argv, &streamObj);
51 }
52 if (status != napi_ok) {
53 HILOGE("create stream obj fail");
54 return nullptr;
55 }
56 return NVal(env, streamObj).val_;
57 }
58
Read(napi_env env,napi_callback_info info)59 napi_value CreateStreamRw::Read(napi_env env, napi_callback_info info)
60 {
61 return CreateStream(env, info, READ_STREAM_CLASS);
62 }
63
Write(napi_env env,napi_callback_info info)64 napi_value CreateStreamRw::Write(napi_env env, napi_callback_info info)
65 {
66 return CreateStream(env, info, WRITE_STREAM_CLASS);
67 }
68 } // namespace ModuleFileIO
69 } // namespace FileManagement
70 } // namespace OHOS